首页 > 解决方案 > 这个 DateTime 的 JSON 格式模式是什么?

问题描述

这个日期时间字符串的 JsonFormat 模式是什么?

"2021-02-16Z09:38:35"

它已被定义为字符串(ISO 日期时间格式)。

我将其定义为 -

@JsonProperty("lastDT")
@JsonFormat(pattern = "yyyy-MM-dd'Z'HH:mm:ss", shape = JsonFormat.Shape.STRING)
private ZonedDateTime lastDT;

我不断收到 JSON 解析错误

Failed to deserialize java.time.ZonedDateTime: (java.time.DateTimeException) Unable to obtain 
ZonedDateTime from TemporalAccessor: {},ISO resolved to 2021-02-16T09:38:35 of type java.time.format.Parsed

标签: javaspringdatetime

解决方案


ISO 8601 格式,拙劣

您询问:

这个日期时间字符串的 JsonFormat 模式是什么?

"2021-02-16Z09:38:35"

看起来有人尝试使用标准ISO 8601格式但失败了。

T在 ISO 8601 中,字符串的日期部分和时间部分之间应该有一个。

正确的格式应该是2021-02-16T09:38:35而不是2021-02-16Z09:38:35用一个T,而不是Z

我建议您对数据源的发布者进行有关正确使用 ISO 8601 的教育。

使用LocalDateTime,而不是ZonedDateTime

类似的字符串2021-02-16T09:38:35表示日期和时间,但缺少时区或与 UTC 的偏移量的任何指示。因此,您应该将代码更改为使用LocalDateTime而不是ZonedDateTime.

String inputCorrected = "2021-02-16Z09:38:35".replace( "Z" , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( inputCorrected ) ;

祖鲁时间

AZ在 ISO 8601 中用于表示与 UTC 的零时分秒偏移量。根据航空/军事传统,这封信发音为“Zulu”。

Instant instant = Instant.now() ;    // Represent a moment as seen in UTC, an offset of zero hours-minutes-seconds from UTC.
String output = instant.toString() ;

2021-02-16T09:38:35Z


推荐阅读