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

Anu*_*rma 2 java

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

我一直在尝试在乔达时间做类似以下的事情:

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

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

And*_*eas 5

虽然问题代码使用了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
}
Run Code Online (Sandbox Code Playgroud)