【问题标题】:How to convert UTC Time to LocalDateTime by using ZonedDateTime如何使用 ZonedDateTime 将 UTC 时间转换为 LocalDateTime
【发布时间】:2020-01-11 21:17:38
【问题描述】:

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

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

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


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

【问题讨论】:

    标签: java utc localdate zoneddatetime java-time


    【解决方案1】:

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

    为什么? LocalDateTime(混淆类名)是一个没有时区或偏移量的日期和时间。不存储已知的偏移量或时区会丢弃重要数据,并且是等待发生的错误。

    一个例外:对于未来某个已知时区的日期和时间,请务必存储 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);
    

    将时区设置为 Asia/Istanbul 后,此 sn-p 输出:

    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

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 2016-04-10
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2014-11-16
      • 2019-01-21
      • 2017-10-15
      相关资源
      最近更新 更多