问题描述
对于给定格式的字段,我有一个值为 2020-03-07T04:11:20.000 的JSON文件 yyyy-MM-dd'T'HH:mm:ss.SSS 。我试图在其末尾添加一个Z,但它始终使验证失败。 知道为什么吗?
我试图做 OffsetDateTime.parse(mytext,DateTimeFormatter.ofPattern(mypattern)) 并且它抛出DateTimeParseException并无法从TemporalAccessor获取OffsetDateTime
解决方法
由于模式和输入都没有时区偏移,因此无法将其直接解析为OffsetDateTime
。您可以做的是将日期解析为LocalDateTime
,然后将偏移量添加到结果中。
例如,使用ZoneOffset.UTC:
LocalDateTime ldt = LocalDateTime.parse(mytext,DateTimeFormatter.ofPattern(mypattern));
OffsetDateTime odt = ldt.atOffset(ZoneOffset.UTC)
,
首先,您使用的是错误的类OffsetDateTime
。由于您已经提到timezone="UTC"
,因此您应该使用ZonedDateTime
。请注意,使用以下注释后,生成的日期时间将类似于2020-03-07T04:11:20.000 UTC
。
@JsonFormat(shape=JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS z",timezone="UTC")
您可以使用ZonedDateTime
模式将其解析为yyyy-MM-dd'T'HH:mm:ss.SSS z
。
演示:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String myPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS z";
String myText = "2020-03-07T04:11:20.000 UTC";
System.out.println(ZonedDateTime.parse(myText,DateTimeFormatter.ofPattern(myPattern)));
}
}
输出:
2020-03-07T04:11:20Z[UTC]
如果要将日期时间格式保留为2020-03-07T04:11:20.000
,则应从注释中删除timezone="UTC"
,然后将获取的日期时间字符串解析为LocalDateTime
而不是{{ 1}}。不用说,在这种情况下,模式应为ZonedDateTime
。