如何保存UTC时间戳?
问题描述:
如何将ZonedDateTime
转换为SQL Timestamp
并保留时区信息? 我试图采取UTC划的时间,将其转换为Timestamp
,然后将其转换回来,但是当我转换为Timestamp
,它失去的时区信息和Timestamp
在使用我的本地时区创建:如何保存UTC时间戳?
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
记录使用正确的时区信息?
答
当我转换为时间戳,它失去的时区信息,并使用我的本地时区
号当您转换原有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
。
您可以使用'&server Timezone = UTC&使用传统日期时间代码= false'成功 –
SQL时间戳不*具有*时区 - 这只是时间上的即时。如果您需要单独的时区,我建议将时区ID存储在单独的列中。如果您只关心该时间点的偏移量,则可以存储该偏移量 - 但您需要知道,这与存储时区不同。 –
我的理解与存储时区不同,但我需要能够将时区绝对时间存储在UTC时区的瞬间。我不允许修改数据库表。所以如果我在纽约纽约时间下午3点,它需要存储为11AM,同样如果我在伦敦,并且是4PM,它需要存储为3PM。否则,我从数据库中检索'Timestamp'时没有参考点。 – DayTripperID