I'm new to java.time package. I have a LocalDate 2015-12-10. I need to convert this to ZonedDateTime. Time should be 00:00:00 and Zone is ZoneOffset.UTC.
After conversion, ZonedDateTime should be 2015-12-10T00:00:00+02:00.
I'm storing the LocalDate in a variable called startDate.
I tried:
ZonedDateTime.ofInstant(Instant.from(startDate), ZoneOffset.UTC)
but get the error
java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: 2015-12-10 of type java.time.LocalDate]
I also tried:
startDate.atStartOfDay().atZone(ZoneOffset.UTC)
This gives unexpected results.
I looked at the API and tried a few other methods, but no luck so far.
Is there any other way to convert LocalDate to ZonedDateTime?
Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime to ZonedDateTime , we can use . atZone(ZoneId. systemDefault()) to create a ZonedDateTime containing the system default time zone and convert it to another time zone using a predefined zone id or offset.
To convert a LocalDateTime to another time zone, you first apply the original time zone using atZone() , which returns a ZonedDateTime , then convert to the new time zone using withZoneSameInstant() , and finally convert the result back to a LocalDateTime . If you skip the last step, you'd keep the zone.
Step 1: use the Date. toInstant() method to convert the Date object to an Instant object. Step 2: use the Instant. atZone(ZoneId zone) method to convert the Instant object of step 1 to a ZonedDateTime object in UTC time zone.
LocalDateTime – same as LocalDate, but includes time with nanosecond precision. OffsetDateTime – same as LocalDateTime, but with time zone offset. LocalTime – time with nanosecond precision and without date information. ZonedDateTime – same as OffsetDateTime, but includes a time zone ID.
When converting less specific objects to more specific ones, use the 'at' methods:
ZonedDateTime zdt = startDate.atStartOfDay(ZoneOffset.UTC);
Passing in the UTC offset will not get a result of +02:00 however, which suggests you are trying to achieve something else.
I supose the issue isn't relevant anymore but for google-purposes:
LocalDate localDate = LocalDate.parse("2017-07-22"); ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); // => 2017-07-22T00:00+05:30[Asia/Kolkata]
source https://beginnersbook.com/2017/10/java-convert-localdate-to-zoneddatetime/
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