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

标签 java utc localdate zoneddatetime java-time

我找到了很多将 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/

相关文章:

java - 记住扫描仪中的位置

java swing组件无法解析

asp.net - 如何使用 UTC 时间(asp.net 和 ajax)向用户呈现本地时间

java - 支持跨时区和夏令时变化的重复事件

java - 将大写日期解析为 LocalDate

java - jackson :将时代反序列化为 LocalDate

java - 如何使用 ant 构建 jar 文件?

java - 如何创建自定义 SQLite 函数并在 Cayenne 下执行

Java 使用 Joda 将 UTC 日期转换为本地日期

java - java 将字符串转换为日期时间