This quick Java 8 coding tip shows how to convert
java.time.LocalDate, along with conversion from
java.time.LocalDateTime. This tip is especially useful for those who are migrating their old code in Java 7 to Java 8 code, while some of the external libraries being used are still in Java 7 and hence returning
java.util.Date values. It is recommended that Java 8 code should use Date-Time classes from the new
java.time package and not the earlier
java.util based date classes.
- The above example starts with creating a new
java7Date. This creates an instance of
Datecontaining date, time and time zone as per the system on which the JVM is running.
- Next we convert
java7Dateto an equivalent instance of
java.time.LocalDateTime. This conversion is done in 3-steps –
java7Date.toInstant()is invoked. This returns an instance of
java.time.Instantwhich contains the date,time, and time zone extracted from
Instant.atZone(ZoneId zoneId)method is used, with the value for
ZoneId.systemDefault()method internally reads the time zone of the system clock on the machine on which JVM is running. This method returns a
java.time.ZonedDateTimeinstance. If you are new to
ZonedDateTimethen you can read the detailed tutorial on Java 8 time zonesClick to read Java 8 Time Zones tutorial.
ZonedDateTime.toLocalDateTime()method is invoked on the
ZonedDateTimeinstance obtained in previous step. This gives us the desired
java.time.LocalDateTimeinstance which is equivalent to
LocalDateTimeis straightforward, and is accomplished using the
- The values for
java7Datealong with equivalent
LocalDateTimevalues are printed, and as expected they all match.