Tuesday, August 16, 2016

How to convert date into datetime in java

Java 8 has adopted Jodatime in Jave SE8. Joda time is now introduced in java.time package.

Joda time was de facto standard date and time library prior to Java SE8.

 Following are the ways to convert the java util dates with java.time.* and vice-versa.

The idle way (for all these conversions) is to convert to Instant. This can be converted to LocalDateTime by telling the system which timezone to use. This needs to be the system default locale, otherwise the time will change.

Convert java.util.Date to java.time.LocalDateTime


Date ts = new Date();
Instant instant = Instant.ofEpochMilli(ts.getTime());

LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());


Convert java.util.Date to java.time.LocalDate

Date date = new Date();
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDate res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();

Convert java.util.Date to java.time.LocalTime

Date time = new Date();
Instant instant = Instant.ofEpochMilli(time.getTime());
LocalTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();

Convert java.time.LocalDateTime to java.util.Date

LocalDateTime ldt = LocalDateTime.now();
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);

Convert java.time.LocalDate to java.util.Date

LocalDate ld =  LocalDate.now();

Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);

Convert java.time.LocalTime to java.util.Date

LocalTime lt = LocalTime.now();
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
        atZone(ZoneId.systemDefault()).toInstant();

Date time = Date.from(instant);

A list of key features provided at joda-time official website:

A selection of key features:
  • LocalDate - date without time
  • LocalTime - time without date
  • Instant - an instantaneous point on the time-line
  • DateTime - full date and time with time-zone
  • DateTimeZone - a better time-zone
  • Duration and Period - amounts of time
  • Interval - the time between two instants

3 comments:

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...