ZoneId 和 LocalDateTime

ZoneId and LocalDateTime

我 运行 这段代码现在在巴黎,12:40,其中 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());

但我在控制台得到这个

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

我不应该得到 12:40 ????????

不,你不应该。您要求 ZonedDateTime 与您开始使用的 LocalDateTime 相同,但与特定时区相关联。

来自 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.

在这种情况下不需要调整,因为 2017-05-16T10:40:07.882 did 发生在巴黎。

听起来您的错误根本在于创建 LocalDateTime。你基本上说 "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."

如果您的目标是获取 zone 中的当前时间,则根本不应该有 LocalDateTime。只需使用:

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

或(等价地)

ZonedDateTime zonedNow = Clock.systemUTC().instant().atZone(zone);

此方法 return 是 ZonedDateTime,不是修改后的 LocalDateTime。因此,在这种情况下,它将 return 代表 2017-05-16 10:40 时区 ETC 的 ZonedDateTime