gpt4 book ai didi

java - 如何保存 UTC 时间戳?

转载 作者:行者123 更新时间:2023-12-02 02:51:06 28 4
gpt4 key购买 nike

如何将 ZonedDateTime 转换为 SQL Timestamp 并保留时区信息?我正在尝试获取 UTC 分区时间,将其转换为 Timestamp,然后将其转换回来,但是当我转换为 Timestamp 时,它会丢失时区信息,并且时间戳是使用我的本地时区创建的:

public static void main(String[] args) {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");

ZonedDateTime zdtUTC = ZonedDateTime.now(ZoneId.of("UTC"));

ZonedDateTime zdtNY = zdtUTC.withZoneSameInstant(ZoneId.of("America/New_York"));
ZonedDateTime zdtAZ = zdtUTC.withZoneSameInstant(ZoneId.of("America/Phoenix"));
ZonedDateTime zdtUK = zdtUTC.withZoneSameInstant(ZoneId.of("Europe/London"));

System.out.println(formatter.format(zdtUTC) + " in UTC zone");
System.out.println(formatter.format(zdtNY) + " in New York, NY");
System.out.println(formatter.format(zdtAZ) + " in Phoenix, AZ");
System.out.println(formatter.format(zdtUK) + " in London, UK");

Timestamp timestamp = Timestamp.from(zdtUTC.toInstant());

LocalDateTime converted = timestamp.toLocalDateTime();
ZonedDateTime convertedZdt = ZonedDateTime.of(converted, ZoneId.of("UTC"));

System.out.println(timestamp);

System.out.println(formatter.format(convertedZdt) + " in UTC zone");

}

06:33 PM in UTC zone
02:33 PM in New York, NY
11:33 AM in Phoenix, AZ
07:33 PM in London, UK
2017-05-07 14:33:06.745
02:33 PM in UTC zone

我需要做什么才能确保 Timestamp 记录使用正确的时区信息?

最佳答案

when I convert to Timestamp, it loses the time zone info and the Timestamp is created using my local time zone

没有。当您将原始 ZonedDateTime zdtUTC 转换为 java.sql.Timestamp 时,您会得到相同的时间点。这可以通过直接格式化并显示 timestamp 值来验证:

Timestamp timestamp = Timestamp.from(zdtUTC.toInstant());  // as before
// verify the timestamp value directly
java.text.SimpleDateFormat sdfUTC = new java.text.SimpleDateFormat("hh:mm a z");
sdfUTC.setCalendar(java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC")));
System.out.printf("timestamp is %s%n", sdfUTC.format(timestamp));

这将打印与输出第一行相同的值:

08:30 PM in UTC zone
...
timestamp is 08:30 PM UTC

随后转换为 LocalDateTime,然后再转换回 ZonedDateTime,从而“丢失”了时区信息。

关于java - 如何保存 UTC 时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43835258/

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