How do I make java.sql.Timestamp UTC time?(如何使 java.sql.Timestamp UTC 时间?)
问题描述
public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
Instant instant = Instant.from(zdt);
Timestamp timestamp = Timestamp.from(instant);
System.out.println(ldt + "
");
System.out.println(zdt + "
");
System.out.println(instant + "
");
System.out.println(timestamp + "
");
}
然后打印出来:
2017-05-07T18:13:26.969
2017-05-07T18:13:26.969-04:00[America/New_York]
2017-05-07T22:13:26.969Z
2017-05-07 18:13:26.969
如何使 SQL Timestamp
与 Instant
的保存时间相同?我需要能够从任何地方获取 Timestamp
并将其转换为它碰巧在世界那个地方的任何时间.问题是它一直保存与我的系统时钟设置的时间相同.
How can I make an SQL Timestamp
save with the same time as the Instant
? I need to be able to get the Timestamp
from anywhere and convert it to whatever time it happens to be in that part of the world. The problem is that it keeps saving as the same time as whatever my system clock happens to be set at.
推荐答案
你最好从 LocalDateTime
中获取 Timestamp
,而不是从 Instant
.
You are best to get a Timestamp
from a LocalDateTime
, rather than from an Instant
.
第一步是获取您的 ZonedDateTime
并将其转换为 GMT:
The first step is to take your ZonedDateTime
and convert it to GMT:
ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT"));
然后您可以通过 LocalDateTime
将其转换为 Timestamp
:
Then you can convert it to a Timestamp
via a LocalDateTime
:
Timestamp timestamp = Timestamp.valueOf(gmt.toLocalDateTime());
这篇关于如何使 java.sql.Timestamp UTC 时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 java.sql.Timestamp UTC 时间?
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01