日期时间格式化程序可以解析,但不能为相同的输入设置格式



模式"yyyy_'w'w"DateTimeFormatter无法格式化它已解析的值。

val df = DateTimeFormatter.ofPattern("yyyy_'w'w")
df: DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)'_''w'Localized(WeekOfWeekBasedYear,1)
val week = df.parse("2017_w19")
week: temporal.TemporalAccessor = {Year=2017, WeekOfWeekBasedYear[WeekFields[SUNDAY,1]]=19},ISO
df.format(week)

错误是:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
java.time.format.Parsed.getLong(Parsed.java:203)
java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540)
java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)

这是为什么呢?

模式yyyy表示纪元年份字段。但是根据javadoc的说法,还有表示年份字段的模式uuuu(阅读这些链接以查看它们之间的微小差异 - 尽管对于当前日期没有太大区别(。

问题是:当您使用y创建格式化程序时,它使用纪元年份字段,如值所示:

值(时代年份,4,19,EXCEEDS_PAD(

但是在解析时,生成的解析对象(在您的情况下为week变量(是使用year字段创建的 - 如值所示:

{年份=2017, ...


格式化程序设置了时代年份字段。因此,当您尝试格式化week时,它会尝试从week变量中获取此字段。由于此字段不存在(week仅包含年份,但不包含纪元年份(,因此会抛出UnsupportedTemporalTypeException

解决方案是在格式化程序中使用year字段(u模式(:

val df = DateTimeFormatter.ofPattern("uuuu_'w'w")
println(df)
val week = df.parse("2017_w19")
println(week)
println(df.format(week))

输出将是:

Value(Year,4,19,EXCEEDS_PAD('_''w'Localized(WeekOfWeekBasedYear,1(
{Year=2017, WeekOfWeekBasedYear[WeekFields[SUNDAY,1]]=19},ISO 2017_w19

请注意,现在格式化程序是使用year字段创建的,format方法现在尝试从解析的对象中获取此字段,并且不会引发异常。

对我来说,你不能使用DateTimeFormatter来格式化TemporalAccessor,这是一个过于宽泛的时间接口。首先尝试将其强制转换为 DateTime 对象。

最新更新