我找到了很多将 localDateTime 转换为 UTC 格式的 LocalDateTime 的方法。 但我找不到任何方法使用 ZonedDateTime 将 UTC 时间转换为 localDateTime。你知道如何转换它吗?
这就是我用来将其转换为 UTC 的方法。我需要一种反之亦然的方法。
ZonedDateTime zonedDate = ZonedDateTime.of(localDateTime,
ZoneId.systemDefault());
localDateTime.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC)
最佳答案
请勿将 LocalDateTime
用于您知道 UTC 偏移量或时区的日期和时间。对于您所在时区或其他已知时区的日期和时间,请使用 ZonedDateTime
。对于已知偏移量的日期和时间(此处 UTC 算作偏移量),请使用 OOffsetDateTime
。
LocalDateTime
(令人困惑的类名)是没有时区或偏移量的日期和时间。不存储已知的偏移量或时区会丢弃重要数据,并且可能会发生错误。
一个异常(exception):对于 future 已知时区的日期和时间,请存储 LocalDateTime
并确保将时区存储为单独的 ZoneId
对象。这将允许时区的偏移量和/或夏令时规则(DST 规则)在现在和那个时间之间发生变化(这种情况发生的频率比我们想象的要高)。只有当时间临近并且我们的Java安装可能已经更新为最新的区域规则时,我们才能正确地将日期时间和区域结合起来并获得正确的时间时刻。
将 UTC 日期和时间转换为您所在的时区
OffsetDateTime utcDateTime = OffsetDateTime.of(2019, 9, 10, 12, 0, 0, 0, ZoneOffset.UTC);
System.out.println("UTC date and time: " + utcDateTime);
ZonedDateTime myDateTime = utcDateTime.atZoneSameInstant(ZoneId.systemDefault());
System.out.println("Date and time in the default time zone: " + myDateTime);
将时区设置为亚洲/伊斯坦 boolean 后,此代码段输出:
UTC date and time: 2019-09-10T12:00Z Date and time in the default time zone: 2019-09-10T15:00+03:00[Asia/Istanbul]
从您所在的时区转换为 UTC
对于相反的转换,我更喜欢:
OffsetDateTime convertedBackToUtc = myDateTime.toOffsetDateTime()
.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("UTC date and time again: " + convertedBackToUtc);
UTC date and time again: 2019-09-10T12:00Z
仍然没有使用任何LocalDateTime
。
关于java - 如何使用 ZonedDateTime 将 UTC 时间转换为 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57865304/