gpt4 book ai didi

java - ZoneId 和 LocalDateTime

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:43 32 4
gpt4 key购买 nike

我现在正在巴黎运行这段代码,时间是 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 确实发生在巴黎。

听起来您的错误根本在于创建了 LocalDateTime。您基本上是在说“找出 UTC 的当前时间,然后采用相同的本地日期和时间,但假装它处于不同的时区。”

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

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

或(等价地)

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

关于java - ZoneId 和 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999265/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com