首页 > 解决方案 > 如何在 Kotlin 中向 LocalDateTime 对象添加时区偏移量?

问题描述

我正在努力将时区为 UTC 的 LocalDateTime 对象转换为韩国标准时间(KST,+09:00)并获取时间戳。我想将2021-04-20T03:00:00(UTC) 更改为2021-04-20T12:00:00(KST)。

从数据库中获取了一个 UTC LocalDateTime 对象。

/*
+----+---------------------+
| id | created_at          |
+----+---------------------+
| 0  | 2021-04-20T03:00:00 |
+----+---------------------+
*/

val createdAt: LocalDateTime = db.select(created_at).where(id.eq(0)) // 2021-04-20T03:00:00

然后,我尝试使用 OffsetDateTime 将对象的时区更改为 KST(+09:00)。

val kstCreatedAt = OffsetDateTime.of(createdAt, ZoneOffset.of("+9"))
                   // I expected this is 2021-04-20T12:00:00

我的最终目标是获得2021-04-20T12:00:00.

kstCreatedAt.toInstant().toEpochMilli() // 1618855200000 (The timestamp of 2021-04-20T03:00:00)
                     // I expected this is 1618887600000 (The timestamp of 2021-04-20T12:00:00)

我预计变量kstCreatedAt2021-04-20T12:00:00,但它仍然是2021-04-20T03:00:00,最后一个值是2021-04-20T03:00:00not的时间戳2021-04-20T12:00:00。如何将时区偏移量(+9)添加到 LocalDateTime 对象?

标签: datetimekotlintimezone

解决方案


推荐阅读