gpt4 book ai didi

android - Joda DateTime 时区未正确显示

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:22 25 4
gpt4 key购买 nike

我在 Android 中使用 Joda-Time DateTime

DateTimeZone 似乎无法正常工作。也许这与夏令时有关?

此刻,我们有 GMT +2。这将在几周后改变,因为冬天。然后是 GMT +1。但现在是不正确的。

import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.LocalDateTime

// GMT: Thursday 26 October 2017 12:11:54
val epochTime: Long = 1509019914

var dateServer = LocalDateTime(epochTime * 1000).toDateTime(DateTimeZone.forID("Europe/Amsterdam"))

预计(阿姆斯特丹的正确时间):

14:11:54 GMT+02:00 DST

实际:

13:11 2017-10-26T13:11:54.000+01:00

最佳答案

LocalDateTime 构造函数获取 epochTime 值和 converts to the default timezone获取日期和时间值 - 检查 DateTimeZone.getDefault() 的值,它可能是当前使用 +01:00 偏移量的时区。

然后 toDateTime 方法创建一个 DateTime,它对应于由 LocalDateTime 表示的相同日期和时间,但在指定的时区 (它只是将时区“附加”到日期/时间值,不进行任何转换。

如果要获取特定时区的epochTime对应的日期和时间,只需create the DateTime directly :

val dateServer = DateTime(epochTime * 1000, DateTimeZone.forID("Europe/Amsterdam"));

这样,dateServer 将是:

2017-10-26T14:11:54.000+02:00


我的默认时区的一个例子,只是为了更清楚。我的默认时区(由 DateTimeZone.getDefault() 返回)是 America/Sao_Paulo,它使用偏移量 -02:00(2 小时2017 年 10 月 26 日

epochTime 1509019914 对应 UTC 2017-10-26T12:11:54Z

当我执行 LocalDateTime(epochTime * 1000) 时,它会获取相应的 UTC 值 (12:11) 并转换为默认时区:在我的例子中为 10:11,因此 LocalDateTime 的值为 2017-10-26T10:11:54

然后 toDateTime 方法只创建一个 DateTime 对应于相同的日期和时间 (2017-10-26T10:11:54 ), 在指定的时区。因此它在阿姆斯特丹 (+02:00) 创建 2017-10-26T10:11:54

您的默认时区可能是使用 +01:00 偏移量的时区,这可以解释您得到的差异(12:11 UTC 首先转换为 LocalDateTime 13:11,然后 toDateTime 在阿姆斯特丹创建 13:11。


JSR310 - 新的日期/时间 API

Joda-Time 处于维护模式,正在被新的 API 取代,所以我不建议用它开始一个新项目。即使在 joda's website它说:“请注意,Joda-Time 被认为是一个基本“完成”的项目。没有计划进行重大增强。如果使用 Java SE 8,请迁移到 java.time (JSR-310)。” .

如果您不能(或不想)从 Joda-Time 迁移到新 API,您可以忽略此部分。

在 Android 中,您可以使用 ThreeTen Backport ,一个很好的 backport Java 8's new date/time classes .要使其正常工作,您还需要 ThreeTenABP (更多关于如何使用它的信息 here)。

要从 epochTime 获取相应的 UTC 时刻,您可以使用 org.threeten.bp.Instant 类。然后使用 org.threeten.bp.ZoneId 将其转换为时区,从而生成 org.threeten.bp.ZonedDateTime:

val dateServer = Instant.ofEpochSecond(epochTime).atZone(ZoneId.of("Europe/Amsterdam"));

dateServer 将是一个 org.threeten.bp.ZonedDateTime,其值对应于 2017-10-26T14:11:54+02:00 [欧洲/阿姆斯特丹]

关于android - Joda DateTime 时区未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46954570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com