Val*_* K. 5 java timezone-offset
我需要以秒为单位获取本地时间和 UTC 时间。我在 StackOverflow 中阅读了一些帖子并找到了一些解决方案,正如前面提到的那样:
Instant time = Instant.now();
OffsetDateTime utc = time.atOffset(ZoneOffset.UTC);
int utcTime = (int) utc.toEpochSecond();
int localTime = (int) time.getEpochSecond();
System.out.println("utc " + utcTime + " local " + localTime);
Run Code Online (Sandbox Code Playgroud)
但结果并不是我所期望的。现在是UTC时间。输出:
utc 1593762925
local 1593762925
Run Code Online (Sandbox Code Playgroud)
调试后我发现 Instant.now() 已经是 utc。我找不到如何在当前时区(即我的系统区域)中获取时间。
我在 API 中找到了一些解决方案,但出现错误:
OffsetDateTime utc = time.atOffset(ZoneOffset.of(ZoneOffset.systemDefault().getId()));
Run Code Online (Sandbox Code Playgroud)
线程“main”中的异常 java.time.DateTimeException:ZoneOffset 的 ID 无效,格式无效:Europe/Astrakhan 在 java.base/java.time.ZoneOffset.of(ZoneOffset.java:241)
UPD:我的问题是如何在本地时区和 UTC 中以秒为单位获取当前时间?即自 1970-01-01T00:00:00 GMT+4 和 1970-01-01T00:00:00 GMT+0 以来的秒数
UPD2:我有一些设备需要从 1970 年开始以秒为单位的 UTC 时间和以秒为单位的发件人本地时间响应。为什么?我不知道。对我来说是黑匣子。
我认为您需要通过应用 aInstant创建一个ZonedDateTime(OffsetDateTime也可能合适),ZoneId.of("UTC")然后使用ZonedDateTime它来转换区域设置:
public static void main(String[] args) {
Instant now = Instant.now();
ZonedDateTime utcZdt = now.atZone(ZoneId.of("UTC"));
ZonedDateTime localZdt = utcZdt.withZoneSameLocal(ZoneId.systemDefault());
System.out.println(utcZdt.toEpochSecond() + " <== " + utcZdt);
System.out.println(localZdt.toEpochSecond() + " <== " + localZdt);
}
Run Code Online (Sandbox Code Playgroud)
在我的系统上,输出
public static void main(String[] args) {
Instant now = Instant.now();
ZonedDateTime utcZdt = now.atZone(ZoneId.of("UTC"));
ZonedDateTime localZdt = utcZdt.withZoneSameLocal(ZoneId.systemDefault());
System.out.println(utcZdt.toEpochSecond() + " <== " + utcZdt);
System.out.println(localZdt.toEpochSecond() + " <== " + localZdt);
}
Run Code Online (Sandbox Code Playgroud)
两个小时的差异影响纪元秒的第六位数字。