如何保存UTC时间戳?

时间:2017-05-07 18:40:48

标签: java jdbc timestamp zoneddatetime

如何将ZonedDateTime转换为SQL Timestamp并保留时区信息? 我正在尝试接受UTC分区时间,将其转换为Timestamp,然后将其转换回来,但当我转换为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记录使用正确的时区信息?

1 个答案:

答案 0 :(得分:2)

  

当我转换为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"失败"时区信息。