gpt4 book ai didi

java - 为什么 Java 8 Instant.now() 在我的本地服务器上显示错误的 UTC?

转载 作者:行者123 更新时间:2023-12-01 19:45:22 35 4
gpt4 key购买 nike

Java8 Instant.now() 给出已采用 UTC 格式的当前时间。我在 CompileJava.net 上创建了一个简单的沙箱测试验证我的预期结果:

Timestamp createdDateUtc = Timestamp.from(Instant.now());
System.out.println(createdDateUtc);

LocalDateTime databaseUtcLocal = createdDateUtc.toLocalDateTime();
ZonedDateTime databaseUtcZoned = databaseUtcLocal.atZone(ZoneId.of("UTC"));
ZonedDateTime userTimezoneTime = databaseUtcZoned.withZoneSameInstant(ZoneId.of("Asia/Qatar"));
System.out.println(userTimezoneTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a")));

注意:当前时间为 2018 年 12 月 1 日上午 11:16 UTC。

当我在在线编译器上运行此代码时,我得到输出:

2018-12-01 11:17:43.637
12/01/2018 02:17:43 PM

但是当我在本地 JBOSS 服务器上运行此代码时,我得到以下输出:

2018-12-01 03:18:07.464
12/01/2018 06:18:07 AM

这里可能出了什么问题?我的服务器 UTC 时钟是否不正确?我的本地服务器的物理位置位于加利福尼亚州。虽然这并不重要,但当我尝试使用 Instant.now() 显示 UTC 时间时,我却得到了太平洋时间,这似乎很奇怪。

非常感谢任何帮助!

更新

正如已接受的答案所指出的,问题是我的 Timestamp.from() 方法:

System.out.println(Instant.now());
System.out.println(Timestamp.from(Instant.now()));

输出:

2018-12-01T11:48:33.153Z
2018-12-01 03:48:33.171

所以现在我的问题发生了变化。如果您有类似的问题,我在 Stack Overflow here 上找到了我的答案。我使用了这个丑陋的困惑,而不是 Timestamp.from(Instant.now()) :

Timestamp.valueOf(ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime())

最佳答案

我认为 Timestamp.toString() 方法有问题。如果你仔细观察它的内部,你会看到:

public String toString () {

int year = super.getYear() + 1900;
int month = super.getMonth() + 1;
int day = super.getDate();
int hour = super.getHours();
int minute = super.getMinutes();
int second = super.getSeconds();
// other code
}

方法 getHours()getMinutes() 和其他方法来自 Date 类,并根据文档按本地时区 Date.getHours() 进行解释。

关于java - 为什么 Java 8 Instant.now() 在我的本地服务器上显示错误的 UTC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53570315/

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