spring-boot - 如何使用 Java 8 以 UTC 格式存储 DateTime?
问题描述
解决方案
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.
推荐阅读
- python - 用 pyplot 在前景中绘制更近的线条
- email - SpamAssassin:阻止来自除某些域之外的所有域的电子邮件到特定用户
- unity3d - Unity - 命令行性能
- xslt - 使用 XSLT 将 xsd:complex-type 元素复制到另一个 xsd:complex-type 元素
- c# - C# 中的 LoadLibraryEx 函数问题
- python - finally 总是在 try 块返回之前运行,那么为什么 finally 块中的更新不会影响 try 块返回的变量的值?
- javascript - 在反应应用程序的函数调用中使用时,Axios post 不返回数据
- javascript - JavaScript 函数不适用于第二个 HTML 文件,因为它是由第一个 HTML 文件中的按钮触发的
- c - 处理 sbrk() 失败的合规方法是什么?
- java - 如何获取任何编码 Java 字符串的 5 个字符?