【问题标题】:How to identify timezone by string time and convert multiple timezones to one timezone in kotlinkotlin中如何通过字符串时间识别时区并将多个时区转换为一个时区
【发布时间】:2023-02-19 07:01:17
【问题描述】:

我有不同时区的日期时间记录列表

[
    {
        "id": 1,
        "dateTime": "2023-01-01T14:10:24.478Z"
    },
    {
        "id": 2,
        "dateTime": "2023-01-22T08:39:48.374+08:00"
    }.
    {
        "id": 3,
        "dateTime": "2023-01-22T08:39:48.374+05:30"
    }
]

data class Record(val id: Int, val dateTime: String)

我需要将这些所有 dateTime 转换为我的时区(例如:+04:00)

有没有最好的方法来通过 dateTime 值识别时区以将其转换为我的时区?或者我们是否需要子字符串 dateTime 并查找时区值添加自定义方法来获取时区?

例如:

fun String.timezone() : String? {
    return when(this) {
        "+05:30" -> "Asia/Calcutta"
        "Z" -> "UTC"
            .....
        else -> null
    }
}

(如果知道 dateTime 的时区,我知道如何将 dateTime 转换为我的时区)

【问题讨论】:

  • 这些字符串都不表示时区。它们是偏移量,同一时刻同一偏移量中可以有多个不同的时区。然而,价值观确定一个时间点,所以如果你真的您的时区,您可以轻松地将值转换为该时区。您应该将这些字符串解析为 OffsetDateTime 值,因为这就是它们所代表的。

标签: kotlin datetime timezone datetime-conversion


【解决方案1】:

您是在问如何将偏移量映射到时区吗?你不能。在任何时候,几个时区可以巧合地共享相同的偏移量。

你说:

我的时区(例如:+04:00)

更正......你的例子+04:00是UTC的偏移量,不是一个时区。

偏移量仅仅是 UTC 时间本初子午线之前或之后的小时-分钟-秒数。在 Java 中,使用 ZoneOffsetOffsetDateTime

时区是特定地区人民使用的偏移量的过去、现在和未来变化的命名历史,由他们的政治家决定。在 Java 中,将 ZoneIdZonedDateTime 结合使用。

Point on timeline
Offset from UTC ZoneOffset OffsetDateTime
Time zone ZoneId ZonedDateTime

时区的名称格式为Continent/Region。例如,Africa/CasablancaPacific/Auckland。仅供参考,时区 Asia/Calcutta 已重命名为 Asia/Kolkata

将您的输入解析为 OffsetDateTime 对象。

(Java 语法;我不懂 Kotlin)

OffsetDateTime odt = OffsetDateTime.parse( "2023-01-22T08:39:48.374+08:00" ) ;

应用您想要的时区。

ZoneId z = ZoneId.of( "Asia/Dubai" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2011-11-11
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多