如何使 java.sql.Timestamp UTC 时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43837323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make java.sql.Timestamp UTC time?
提问by CptHowdyRD0
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");
}
And it prints:
它打印:
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
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.
如何Timestamp
在同一时间进行 SQL保存Instant
?我需要能够Timestamp
从任何地方获取并将其转换为它恰好在世界该地区的任何时间。问题是它在保存的时间与我的系统时钟碰巧设置的时间相同。
回答by Joe C
You are best to get a Timestamp
from a LocalDateTime
, rather than from an Instant
.
您最好Timestamp
从 a 中获取 a LocalDateTime
,而不是从 an 中获取Instant
。
The first step is to take your ZonedDateTime
and convert it to GMT:
第一步是将您的ZonedDateTime
并将其转换为 GMT:
ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT"));
Then you can convert it to a Timestamp
via a LocalDateTime
:
然后您可以Timestamp
通过 a将其转换为a LocalDateTime
:
Timestamp timestamp = Timestamp.valueOf(gmt.toLocalDateTime());
回答by David A
You might need to use the specific overload of setTimestampthat takes a Calendar object if you want to represent a "TIMESTAMP WITH TIME ZONE" value.
如果要表示“TIMESTAMP WITH TIME ZONE”值,则可能需要使用带有 Calendar 对象的setTimestamp的特定重载。