如何制作java.sql.Timestamp UTC时间? [英] How do I make java.sql.Timestamp UTC time?
问题描述
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 + "\n");
System.out.println(zdt + "\n");
System.out.println(instant + "\n");
System.out.println(timestamp + "\n");
}
并打印出来:
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
如何在 Instant $ c的同时保存SQL
时间戳
保存$ C>?我需要能够从任何地方获得时间戳
并将其转换为它在世界的任何时间。问题在于它与我的系统时钟恰好设置在同一时间保存。
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
获取时间戳
,而不是从 Instant $ c $获得c>。
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
:
Then you can convert it to a Timestamp
via a LocalDateTime
:
Timestamp timestamp = Timestamp.valueOf(gmt.toLocalDateTime());
这篇关于如何制作java.sql.Timestamp UTC时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!