在时区将 ZonedDateTime 转换为 LocalDateTime

新手上路,请多包涵

我有一个对象 ZonedDateTime 是这样构造的

ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);

如何将其转换为瑞士时区的 LocalDateTime ?预期结果应为 16 april 2018 13:30

原文由 Vitalii 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 999
2 个回答

如何将其转换为瑞士时区的 LocalDateTime?

您可以将 UTC ZonedDateTime 转换为 ZonedDateTime 与瑞士时区,但保持相同的即时时间,然后得到 LocalDateTime out of thatf6419 , 如果你需要。我很想将它保留为 ZonedDateTime 除非出于其他原因需要它作为 LocalDateTime

 ZonedDateTime utcZoned = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
ZoneId swissZone = ZoneId.of("Europe/Zurich");
ZonedDateTime swissZoned = utcZoned.withZoneSameInstant(swissZone);
LocalDateTime swissLocal = swissZoned.toLocalDateTime();

原文由 Jon Skeet 发布,翻译遵循 CC BY-SA 3.0 许可协议

它有助于理解 LocalDateTime 和 ZonedDateTime 之间的区别。你真正想要的是 ZonedDateTime 。如果您想从字符串表示中删除时区,您可以将其转换为 LocalDateTime

你要找的是: ZonedDateTime swissZonedDateTime = withZoneSameInstant(ZoneId.of("Europe/Zurich"));

LocalDateTime - 这基本上是 DateTime 的美化字符串表示;它与时区无关,这意味着它不代表时间轴上的任何时间点

Instant - 这是自 EPOCH 以来经过的时间的毫秒表示。这表示时间轴上的特定时刻

ZonedDateTime - 这也表示时间轴上的一个瞬间, 它表示为 DateTime --- 和 —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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题