Converting between Date and java8 java.time.LocalDateTime, LocalDate and LocalTime

Java8 has new date and time classes to “replace” the old not-so-beloved java.util.Date class.

Unfortunately though, converting between the two is somewhat less obvious than you might expect.

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

Date ts = ...;
Instant instant = Instant.ofEpochMilli(ts.getTime());
LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

The big trick (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.LocalDate

Date 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 = ...;
Instant instant = Instant.ofEpochMilli(time.getTime());
LocalTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();

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

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

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

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

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

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

This one is a little, funny, you need to inject a date to convert the time… Gives you the option of start of epoch or something else.

5 Comments

  1. Sven Recknagel says:

    Converting from java.util.Date to an Instant is even easier: There’s a method toInstant() in the Date class that just returns Instant.ofEpochMilli(getTime()) as you posted.

  2. ric says:

    How to convert a LocalDate to an Instant?
    I get an exception with
    LocalDate date = LocalDate.of(2012, 2, 2);
    Instant instant = Instant.from(date);

    • Michael Krog says:

      @ric

      I wondered about that myself. Incredibly insane API design that has no good explanation what so ever.

      It turns out you need to do something like this:
      date.atZone(ZoneId.systemDefault()).toInstant()

  3. 4 years of bloody API development for one to have to do this

    Date.from(date.atZone(ZoneId.systemDefault()).toInstant()) to convert a LocalDate to Date

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen

*