不要将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。