【发布时间】:2021-07-25 00:00:10
【问题描述】:
我很难理解 ZoneDateTime - Instant - LocalDateTime 之间的 java.time ,到目前为止,我唯一知道的是:
- Instant 介于两者之间
- Instant(在我的理解中)是从时刻 (UTC) 算起的时间戳,与人类时间流逝相关的时间戳,但没有时区
- Zone 日期时间有 TimeZone
- Instant 没有时区,但可以在提供时区信息的情况下处理它
- LocalDate 时间没有时区,无法处理时区,它是一个日期时间,与整个时间流(全局)的延续没有任何关系。
所以我在下面有这个转换
val seoul = "Asia/Seoul"
val zoneId = ZoneId.of(seoul)
val now = ZonedDateTime.now()
val convertedZoneDateTIme = ZonedDateTime.of(now.toLocalDateTime(), zoneId).withZoneSameInstant(ZoneOffset.UTC)
val convertedInstant = now.toInstant().atZone(zoneId)
// expected output
println(convertedInstant.format(DateTimeFormatter.ofPattern(format)))
// not expected output
println(converted.format(DateTimeFormatter.ofPattern(format)))
输出
2021-05-02 03:15:13
2021-05-02 09:15:13
我正在尝试将给定时间转换为另一个时区,这是一个用户移动到不同时区的用例,我需要更新有关存储日期的任何信息。
为什么我得到的第二个值不正确..?为什么我必须先将其转换为 Instant 并继续进行转换?
提前谢谢你
【问题讨论】:
-
您的“convertedInstant”不是瞬间,而是
ZonedDateTime。我的建议:使用显式类型而不是val。并选择显示时区的格式。然后你会看到第一个结果是 UTC 而第二个结果是韩国区。
标签: java timezone java-time date-conversion zoneddatetime