Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZoneId and LocalDateTime

I am running this piece of code in Paris right now, where its 12:40, where ECT = ECT - Europe/Paris

LocalDateTime creationDateTime = LocalDateTime.now(Clock.systemUTC());      
ZoneId zone = ZoneId.of(ZoneId.SHORT_IDS.get("ECT"));


System.out.println ("creationDateTime --------------------------> " + creationDateTime);        
System.out.println ("creationDateTime.atZone(zone).getHour() ---> " + creationDateTime.atZone(zone).getHour());
System.out.println ("creationDateTime.atZone(zone).getMinute() -> " + creationDateTime.atZone(zone).getMinute());

But i am getting this at the console

creationDateTime --------------------------> 2017-05-16T10:40:07.882
creationDateTime.atZone(zone).getHour() ---> 10
creationDateTime.atZone(zone).getMinute() -> 40

Shouldn't I get 12:40 ???????

like image 762
La Carbonell Avatar asked Mar 09 '23 02:03

La Carbonell


1 Answers

No, you shouldn't. You've asked for a ZonedDateTime with the same LocalDateTime that you started with, but associated with a particular time zone.

From the docs for LocalDateTime.atZone:

This returns a ZonedDateTime formed from this date-time at the specified time-zone. The result will match this date-time as closely as possible. Time-zone rules, such as daylight savings, mean that not every local date-time is valid for the specified zone, thus the local date-time may be adjusted.

In this case there's no need for adjustment, because 2017-05-16T10:40:07.882 did occur in Paris.

It sounds like your mistake was creating a LocalDateTime at all. You've basically said "Find out what the current time is in UTC, then take the same local date and time, but pretend it's in a different time zone."

If your aim is to get the current time in zone, you shouldn't have a LocalDateTime at all. Just use:

ZonedDateTime zonedNow = ZonedDateTime.now(Clock.system(zone));

or (equivalently)

ZonedDateTime zonedNow = Clock.systemUTC().instant().atZone(zone);
like image 103
Jon Skeet Avatar answered Mar 19 '23 00:03

Jon Skeet