Search code examples
java-8localdatejava.time.instantjava-time

How to convert from Instant to LocalDate


I have an Instant coming from a source that should, according to the specs, be a LocalDate, but don't see any methods in the LocalDate class to convert the Instant to a LocalDate.

What is the best way to do this?


Solution

  • Java 9+

    LocalDate.ofInstant(...) arrived in Java 9.

    Instant instant = Instant.parse("2020-01-23T00:00:00Z");
    ZoneId zone = ZoneId.of("America/Edmonton");
    LocalDate date = LocalDate.ofInstant(instant, zone);
    

    See code run live at IdeOne.com.

    Notice the date is 22nd rather than 23rd as that time zone uses an offset several hours before UTC.

    2020-01-22

    Java 8

    If you are using Java 8, then you could use ZonedDateTime's toLocalDate() method:

    yourInstant.atZone(yourZoneId).toLocalDate()