使用 Material3 Datepicker 调整时区

问题描述 投票:0回答:1

我正在尝试创建一个简单的应用程序,用户需要在其中选择日期。我的问题是,除非我添加区域偏移量,否则它默认为根据 UTC 时间的日期。我的困惑是我认为

val currentZonedDateTime = ZonedDateTime.now(ZoneId.systemDefault())
可以解释时区。我发现我自己必须添加偏移量。 否则下午 6:00 之后默认为第二天。

enter image description here

val currentZonedDateTime = ZonedDateTime.now(ZoneId.systemDefault())
    val zoneOffset = currentZonedDateTime.offset
    val datePickerState = rememberDatePickerState(
        initialSelectedDateMillis = currentZonedDateTime.toInstant().toEpochMilli(),
        //initialSelectedDateMillis = currentZonedDateTime.toInstant().toEpochMilli() +    zoneOffset.totalSeconds * 1000,)

如果我使用调试器,它会显示 currentZonedDateTime 设置为美国/芝加哥。那么为什么它会显示 UTC 时间,除非我在代码中添加添加 zoneOffSet?有更好的方法吗?如果我添加注释代码就可以了。我很困惑为什么我需要这样做。 enter image description here

android kotlin datetimepicker android-jetpack-compose-material3
1个回答
0
投票

那么为什么它会显示 UTC 时间,除非我在代码中添加添加 zoneOffSet?

因为您通过

currentZonedDateTime
currentZonedDateTime.toInstant().toEpochMilli()
转换为实例,并且实例 “是 UTC 时区中的单个时刻”。您基本上将时间戳转换回 UTC 时间。

有更好的方法吗?

如果你所说的更好是指一种无需手动添加偏移量的方法,我不这么认为。我很乐意对此进行纠正,但到目前为止,我还没有找到一种方法可以为您提供自纪元以来的毫秒数(包括时区)。我假设您想要显示用户时区中的日期,并且由于 DatePicker 使用 UTC(尤其是在当天的 00:00 开始时!),您需要对此进行调整。我建议将所有内容存储为 UTC,然后当您需要向用户呈现时间戳时,无论是作为可读字符串还是在本例中通过 DatePicker 对话框,对其进行相应的格式化。

有趣的是,TimePicker 似乎显示了根据您当地时间调整的时间,例如如果您向其提供 UTC 时间戳,您将看到您当前的本地时间,而不是 UTC。

© www.soinside.com 2019 - 2024. All rights reserved.