如何使用 ZonedDateTime 将 UTC 时间转换为 LocalDateTime

How to convert UTC Time to LocalDateTime by using ZonedDateTime

我找到了很多将 localDateTime 转换为 UTC 格式的 LocalDateTime 的方法。 但是我找不到任何方法来使用 ZonedDateTime 在 localDateTime 转换 UTC 时间。你知道转换它的方法吗?

这是我用来将其转换为 UTC 的。我需要反之亦然的方法。

 ZonedDateTime zonedDate = ZonedDateTime.of(localDateTime, 
ZoneId.systemDefault());


localDateTime.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC)

不要将 LocalDateTime 用于您知道 UTC 偏移量或时区的日期和时间。对于您所在时区或其他已知时区的日期和时间,请使用 ZonedDateTime。对于您知道偏移量的日期和时间(此处 UTC 计为偏移量)使用 OFfsetDateTime.

为什么? LocalDateTime(令人困惑的 class 名称)是没有时区或偏移量的日期和时间。不存储已知的偏移量或时区会丢弃重要数据,这是一个等待发生的错误。

一个例外:对于未来已知时区的日期和时间,请存储 LocalDateTime 并确保将时区存储为单独的 ZoneId 对象。这将允许时区的偏移量 and/or 夏令时规则(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);

我将时区设置为 Asia/Istanbul 后,此代码段输出:

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