将 Instant 转换为 LocalDateTime 时的不同值

Different values when converting Instant to LocalDateTime

我从服务器收到 UTC 格式的时间。我解析为 Instant 对象,然后将其转换为 LocalDateTime。像这样:

fun String.toLocaleDateTime(): LocalDateTime {
    return LocalDateTime.ofInstant(
        Instant.parse(this), 
        ZoneOffset.systemDefault()
    )
}

问题是不同年份的 LocalDateTime 对象不同。

例如,将 UTC 时间转换为 IST 时间时:

1800-01-01T03:36:32Z -> 1800-01-01T09:30
1870-01-01T03:36:32Z -> 1870-01-01T08:57:42
1906-01-01T03:36:32Z -> 1906-01-01T09:06:32

Playground

让我们获取印度从 1700 年到 2000 年偏移量的所有变化:

ZoneId.of("Asia/Kolkata").rules.transitions.filter {
    (1700..2000).contains(it.dateTimeBefore.year)
}.forEach {
    println("On ${it.dateTimeBefore}, jumped from ${it.offsetBefore} to ${it.offsetAfter}")
}

这将获取您计算机上 tzdb 版本的时区数据。在我的机器上,打印出:

On 1854-06-28T00:00, jumped from +05:53:28 to +05:53:20
On 1870-01-01T00:00, jumped from +05:53:20 to +05:21:10
On 1906-01-01T00:00, jumped from +05:21:10 to +05:30
On 1941-10-01T00:00, jumped from +05:30 to +06:30
On 1942-05-15T00:00, jumped from +06:30 to +05:30
On 1942-09-01T00:00, jumped from +05:30 to +06:30
On 1945-10-15T00:00, jumped from +06:30 to +05:30

似乎直到 1906 年,印度才使用 local mean time

您的每个结果都反映了这些偏移量:

  • 在 1800 中,偏移量为 +05:53:28,添加到 03:36:32 正好是 09:30
  • 在 1870 年,偏移量是 +05:21:10,添加到 03:36:32 正好是 08:57:42
  • 1906 年,偏移量被标准化为 +05:30,给了您可能期望的答案。