I have an object of ZonedDateTime
that is constructed like this
ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
How can I convert it to LocalDateTime
at time zone of Switzerland? Expected result should be 16 april 2018 13:30
.
Another option that seems a little more intuitive is to convert the zoned date to an instant, then use LocalDateTime.ofInstant:
I prefer this to
withZoneSameInstant
because that solution little more opaque - you're getting a ZonedDateTime that has to be in a particular internal state (the correct time zone). UsingofInstant
can be used on any ZonedDateTime in any time zone.It helps to understand the difference between LocalDateTime and ZonedDateTime. What you really want is a ZonedDateTime. If you wanted to remove the timezone from the string representation, you would convert it to a LocalDateTime.
What you're looking for is: ZonedDateTime swissZonedDateTime = withZoneSameInstant(ZoneId.of("Europe/Zurich"));
LocalDateTime -this is basically a glorified string representation of a Date and Time; it is timezone agnostic, which means it does not represent any point in time on a timeline
Instant - this is a millisecond representation of time that has elapsed since EPOCH. This represents a specific instant in time on a timeline
ZonedDateTime - this also represents an instant in time on a timeline, but it represents it as a Date and Time with a TimeZone.
The code below illustrates how to use all 3.
If you were to compared the Instant values of both ZonedDateTimes from above, they would be equivalent because they both point to the same instant in time. Somewhere in Greenwich (UTC time zone) it is noon on October 25th; at the same time, in New York it would be 8am (America/NewYork time zone).
You can convert the UTC
ZonedDateTime
into aZonedDateTime
with the time zone of Switzerland, but maintaining the same instant in time, and then get theLocalDateTime
out of that, if you need to. I'd be tempted to keep it as aZonedDateTime
unless you need it as aLocalDateTime
for some other reason though.Try this out. Substitute US/Central with your timezone.