我有一个对象 ZonedDateTime
是这样构造的
ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
如何将其转换为瑞士时区的 LocalDateTime
?预期结果应为 16 april 2018 13:30
。
原文由 Vitalii 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个对象 ZonedDateTime
是这样构造的
ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
如何将其转换为瑞士时区的 LocalDateTime
?预期结果应为 16 april 2018 13:30
。
原文由 Vitalii 发布,翻译遵循 CC BY-SA 4.0 许可协议
它有助于理解 LocalDateTime 和 ZonedDateTime 之间的区别。你真正想要的是 ZonedDateTime
。如果您想从字符串表示中删除时区,您可以将其转换为 LocalDateTime
。
你要找的是: ZonedDateTime swissZonedDateTime = withZoneSameInstant(ZoneId.of("Europe/Zurich"));
LocalDateTime - 这基本上是 Date
和 Time
的美化字符串表示;它与时区无关,这意味着它不代表时间轴上的任何时间点
Instant - 这是自 EPOCH 以来经过的时间的毫秒表示。这表示时间轴上的特定时刻
ZonedDateTime - 这也表示时间轴上的一个瞬间, 但 它表示为 Date
和 Time
--- 和 —7438a470b678ab67d5bd57b04e TimeZone
.
下面的代码说明了如何使用所有 3 个。
LocalDateTime localDateTime = LocalDateTime.of(2018, 10, 25, 12, 00, 00); //October 25th at 12:00pm
ZonedDateTime zonedDateTimeInUTC = localDateTime.atZone(ZoneId.of("UTC"));
ZonedDateTime zonedDateTimeInEST = zonedDateTimeInUTC.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println(localDateTime.toString()); // 018-10-25T12:00
System.out.println(zonedDateTimeInUTC.toString()); // 2018-10-25T12:00Z[UTC]
System.out.println(zonedDateTimeInEST.toString()); // 2018-10-25T08:00-04:00[America/New_York]
如果您要比较上面的 Instant
两个 ZonedDateTimes
--- 的值,它们将是等效的,因为它们都指向同一时刻。在格林威治某地(UTC 时区),10 月 25 日正午;同时,在纽约,时间是上午 8 点(美国/纽约时区)。
原文由 Stevers 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
您可以将 UTC
ZonedDateTime
转换为ZonedDateTime
与瑞士时区,但保持相同的即时时间,然后得到LocalDateTime
out of thatf6419 , 如果你需要。我很想将它保留为ZonedDateTime
除非出于其他原因需要它作为LocalDateTime
。