从日历 Android Kotlin 获取 UTC 日期时间戳
我正在尝试以 UTC
格式获取 时区
的日期
,并取决于用户选择的出生地和时区
将其保存在数据库中,但在设置时区并尝试检索新值后,它返回旧格式,而不是 UTC
val calendar = Calendar.getInstance().apply {
timeZone = TimeZone.getTimeZone("UTC")
}
println("Date: ${calendar.time}")
I/System.out: Date: Sat Feb 26 16:43:08 GMT+02:00 2022
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(注:这个答案使用Java语法,因为我没有学过Kotlin。你可以轻松翻译。)
tl;dr
永远不要使用
Calendar
,SimpleDateFormat
,TimeZone< /code>,或其他旧的日期时间类。
使用带有 java.time 类的格式化程序对象生成文本。
请参阅在 IdeOne.com 上实时运行的代码。
从类似于 SQL 标准类型
TIMESTAMP WITH TIME ZONE
类型的数据库列中检索时刻作为OffsetDateTime
对象。调整到您想要的时区。使用DateTimeFormatter
生成文本。详细信息
您正在使用可怕的日期时间类,这些类现在已经成为遗留的,多年前已被 JSR 310 中定义的现代 java.time 类取代。
(Note: This Answer uses Java syntax, as I have not learned Kotlin. You can translate easily.)
tl;dr
Never use
Calendar
,SimpleDateFormat
,TimeZone
, or the other legacy date-time classes.Generate text using a formatter object with the java.time classes.
See this code run live at IdeOne.com.
Retrieve a moment from a database column of a type akin to the SQL-standard type
TIMESTAMP WITH TIME ZONE
as anOffsetDateTime
object. Adjust to your desired time zone. Generate text usingDateTimeFormatter
.Details
You are using terrible date-time classes that are now legacy, years ago supplanted by the modern java.time classes defined in JSR 310.
???? Date-time objects do not have a “format”. Date-time objects hold date-time values, not text. We use formatters to parse text into date-time objects, and use formatters to generate text from date-time objects.
Get current moment as seen in UTC using
Instant
.For more flexible formatting, convert to an
OffsetDateTime
.And use
OffsetDateTime
class when accessing a database column of a type akin to the SQL-standard typeTIMESTAMP WITH TIME ZONE
.To see that same moment as viewed through the wall-clock time used by the people of a particular region, assign a time zone (
ZoneId
) to produce aZonedDateTime
.Generate text in a format that is automatically localized.
See this code run live at IdeOne.com. Notice how the date as well as the time-of-day differs when viewed through the wall-clock time of Japan.
All of this has been covered many many times already on Stack Overflow. Search to learn more.
The java.time classes are built into Java 8 and later. Android 26+ comes bundled with an implementation. For earlier Android, access most of the functionality through the "API desugaring" feature of the latest tooling.