gpt4 book ai didi

java - 将 java.time.Instant 转换为没有区域偏移的 java.sql.Timestamp

转载 作者:IT老高 更新时间:2023-10-28 21:08:03 24 4
gpt4 key购买 nike

在我正在开发的应用程序中,我需要将 java.time.Instant 对象转换为 java.sql.Timestamp。当我创建 Instant 对象时:

Instant now = Instant.now();

我收到类似 2017-03-13T14:28:59.970Z 的信息。当我尝试像这样创建 Timestamp 对象时:

Timestamp current = Timestamp.from(now);

我收到类似 2017-03-13T16:28:59.970Z 的信息。结果相同,但额外延迟了 2 小时。有人可以解释为什么会发生这种情况,并立即为我提供解决此问题的答案吗?

当我这样创建时:

LocalDateTime ldt = LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC);
Timestamp current = Timestamp.valueOf(ldt);

一切正常,但我尽量避免转换。有没有办法只使用 Instant 对象来做到这一点?

最佳答案

我将计算机的时区更改为欧洲/布加勒斯特进行实验。这是 UTC + 2 小时,就像您的时区一样。

现在,当我复制您的代码时,我得到的结果与您的相似:

    Instant now = Instant.now();
System.out.println(now); // prints 2017-03-14T06:16:32.621Z
Timestamp current = Timestamp.from(now);
System.out.println(current); // 2017-03-14 08:16:32.621

输出在注释中给出。但是,我继续:

    DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("UTC"));
// the following prints: Timestamp in UTC: 14-03-2017 06:16:32
System.out.println("Timestamp in UTC: " + df.format(current));

现在您可以看到 Timestamp 确实与我们开始时的 Instant 一致(只有毫秒没有打印,但我相信它们也在那里) .所以你做的一切都是正确的,只是感到困惑,因为当我们打印 Timestamp 时,我们隐式调用了它的 toString 方法,而这个方法又获取了计算机的时区设置和显示该区域的时间。也正因为如此,才表现的不一样。

您尝试的另一件事是使用 LocalDateTime,似乎可以正常工作,但实际上并不能满足您的需求:

    LocalDateTime ldt = LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC);
System.out.println(ldt); // 2017-03-14T06:16:32.819
current = Timestamp.valueOf(ldt);
System.out.println(current); // 2017-03-14 06:16:32.819
System.out.println("Timestamp in UTC: " + df.format(current)); // 14-03-2017 04:16:32

现在,当我们使用我们的 UTC DateFormat 打印 Timestamp 时,我们可以看到它太早了 2 个小时,当 时是 04:16:32 UTC即时 是 06:16:32 UTC。所以这个方法是骗人的,看起来是行得通,其实行不通。

这显示了导致设计 Java 8 日期和时间类以替换旧的类的麻烦。因此,真正解决您的问题的好方法可能是让自己获得一个可以轻松接受 Instant 对象的 JDBC 4.2 驱动程序,这样您就可以完全避免转换为 Timestamp。我不知道你现在是否可以使用,但我相信它会的。

关于java - 将 java.time.Instant 转换为没有区域偏移的 java.sql.Timestamp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766674/

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