首页 > 解决方案 > 如何使用 Java 8 以 UTC 格式存储 DateTime?

问题描述

标签: spring-bootdatetimejava-8date-formattingiso8601

解决方案


The problem with LocalDateTime here is that it simply doesn't store an offset or a time zone, which means you cannot format it to a String that contains a Z for UTC respectively an offset of +00:00.

I would use a ZonedDateTime which will have an offset and a zone id and format is using a specific DateTimeFormatter (don't exactly know how your annotation will handle this).

Here's a small plain Java example:

public static void main(String[] args) {
    // get an example time (the current moment) in UTC
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    // print its toString (implicitly)
    System.out.println(now);
    // format it using a built-in formatter
    System.out.println(now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    // or define a formatter yourself and print the ZonedDateTime using that
    System.out.println(now.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssz")));
}

The output of this small example was (some seconds ago):

2020-10-01T15:06:16.705916600Z
2020-10-01T15:06:16.7059166Z
2020-10-01T15:06:16Z

I think you can use such a pattern in the @JSONFormat annotation. Not entirely sure, but cannot look it up now.


推荐阅读