gpt4 book ai didi

java - 将指定区域的长纪元时间转换为 UTC 长纪元时间

转载 作者:行者123 更新时间:2023-12-03 08:31:28 25 4
gpt4 key购买 nike

我需要将多个区域(变量)的长纪元时间转换为 UTC 中的长纪元时间。

我一直在尝试在 joda-time 中执行以下操作:

long getUTCLong(long timestamp, String timeZone) {
DateTimeZone zone = DateTimeZone.forID(timeZone);
DateTime dt = new DateTime(timestamp, zone);
dt.getMillis();
}

但这不起作用。如何使用新的 java.time 功能来做到这一点

最佳答案

虽然问题代码使用了Joda-Time,但它实际上是在询问使用Java Time API的解决方案,所以这里是:

static long getUTCLong(long timestamp, String timeZone) {
return Instant.ofEpochMilli(timestamp) // process timestamp as milliseconds since 1970-01-01
.atZone(ZoneOffset.UTC).toLocalDateTime() // get pure date/time without timezone
.atZone(ZoneId.of(timeZone)) // mark the date/time as being in given timezone
.toInstant() // convert to UTC
.toEpochMilli(); // get the epoch time in milliseconds since 1970-01-01
}

关于java - 将指定区域的长纪元时间转换为 UTC 长纪元时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64962623/

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