java - Jackson OffsetDateTime 序列化 Z 而不是 +00:00 时区?
问题描述
我正在使用带有以下 ObjectMapper 的 Spring Boot:
@Bean
public ObjectMapper objectMapper()
{
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); // Makes no difference to output
mapper.findAndRegisterModules();
return mapper;
}
当 OffsetDateTimes 被序列化并在响应中返回时,它们的格式如下:
"2020-02-28T12:28:29.01Z"
"2020-02-28T12:36:21.885Z"
我本来希望最后的时区信息看起来像这样:
"2020-02-28T10:41:25.287+00:00"
这里有什么我遗漏或做错的事情,或者无论如何我可以将时区信息序列化为+00:00
格式而不是885Z
格式?
非常感谢!
解决方案
使用预构建格式或为DateTimeFormatter
.
看看这些(非常简单的)例子:
public static void main(String[] arguments) {
Instant now = Instant.now();
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, ZoneId.of("UTC"));
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(now, ZoneId.of("UTC"));
System.out.println(zonedDateTime.toString());
System.out.println(offsetDateTime.toString());
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
System.out.println(zonedDateTime.format(
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
);
System.out.println(offsetDateTime.format(
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx")
)
);
}
我认为您所期望的是最后一个,以 结尾的模式xxx
,这导致偏移量始终以 形式显示HH:mm
,代码示例的输出是:
2020-02-28T12:49:02.388Z[UTC]
2020-02-28T12:49:02.388Z
2020-02-28T12:49:02.388Z[UTC]
2020-02-28T12:49:02.388Z
2020-02-28T12:49:02+0000
2020-02-28T12:49:02+00:00
推荐阅读
- python - 使用 Python csv 模块读取时使用 \r (^M)
- c - 无法编译和链接动态库
- python - pygame中的移动速度
- entity-framework - 如何防止 Entity Framework Core tools 2.1.4 修改目标项目文件?
- php - 如何每 10 次关闭一个 div?
- oracle - 多个 PLS-00103:遇到符号“IN”
- ajax - Popstate 不适用于页面过渡动画
- java - 如何在 Java Spring Web App 中获取项目路径
- laravel - 使用 orWhereHas laravel 雄辩查询检查数据是否存在于另一个表中
- shibboleth - 通过不设置特定路径,使用 Shibboleth SAML/SSO 保护 IIS 中的根目录