固定时钟和本地日期时间

问题描述 投票:0回答:1

出于测试目的,我想创建一个带有时区的固定

Clock

Clock c= Clock.fixed(Instant.parse("2018-04-29T10:15:30.00Z"), ZoneId.of("Europe/Berlin"));
//yields FixedClock[2018-04-29T10:15:30Z,Europe/Berlin]

现在我想使用

Clock
机智
LocalDateTime
:

LocalDateTime.now(c);
//yields 2018-04-29T12:15:30

为什么我要偏移两个小时?有没有 UTC 转换的地方?我需要做什么才能生成带有时区的固定

Clock
并且
LocalDate.now(c)
产生相同的时间?

java java-time
1个回答
0
投票

使用带有固定时钟的 LocalDateTime.now(c) 时,您获得两个小时偏移的原因是 LocalDateTime 和 ZonedDateTime 处理时区和偏移的方式不同。

当您使用 Clock.fixed 创建固定时钟时,您将提供即时 (Instant.parse("2018-04-29T10:15:30.00Z")) 和时区 (ZoneId.of("Europe/Berlin" ))。这意味着时钟固定在特定的时刻和时区。

当您使用 LocalDateTime.now(c) 时,您将从时钟 c 获取 LocalDateTime 对象,该时钟位于欧洲/柏林时区。但是,LocalDateTime 不包含有关时区或偏移量的任何信息。它表示日期和时间,不涉及特定时区或 UTC 偏移量。

您看到两个小时偏移的原因是固定时刻 2018-04-29T10:15:30Z 对应于欧洲/柏林时区,夏令时 (DST) 期间为 UTC+2。当您从这个固定时刻创建 LocalDateTime 时,它不会考虑时区的偏移量,因此它按原样显示时间,而不应用时区的 UTC+2 偏移量。

如果您想生成带有时区的固定时钟并让 LocalDateTime.now(c) 产生相同的时间,则需要使用 ZonedDateTime 而不是 LocalDateTime:

    ZonedDateTime zdt = ZonedDateTime.now(c);
System.out.println(zdt);  // This should match the fixed time and time zone

通过使用 ZonedDateTime,您将获得应用于固定时钟瞬间的正确偏移量和时区。

© www.soinside.com 2019 - 2024. All rights reserved.