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?
Instant instant = Instant. now(); LocalDate localDate = LocalDate. ofInstant(instant, ZoneOffset. UTC);
Conversion Now we will call the atZone() method on the instant object to convert it to a ZonedDateTime object. ZonedDateTime zonedDateTime = instant. atZone(ZoneId. of( "Asia/Kolkata" ));
To convert ZonedDateTime to LocalDate instance, use toLocalDate() method. It returns a LocalDate with the same year, month and day as given date-time. ZonedDateTime zonedDateTime = ZonedDateTime. now(); LocalDate localDate = zonedDateTime.
Parsing String to LocalDateparse() method takes two arguments. The first argument is the string representing the date. And the second optional argument is an instance of DateTimeFormatter specifying any custom pattern. //Default pattern is yyyy-MM-dd LocalDate today = LocalDate.
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
If you are using Java 8, then you could use ZonedDateTime
's toLocalDate()
method:
yourInstant.atZone(yourZoneId).toLocalDate()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With