DateTimeFormatter可以解析,但不能格式化相同的输入
DateTimeFormatter
模式"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
表示year-of-era field。但according to javadoc,也有uuuu
的模式来代表year field(阅读这些链接,看看他们之间的小差异 - 虽然目前的日期没有太大的差异)。
的问题是:当你创建一个格式化与y
,它采用了年的时代场,你可以通过值看:
值(YearOfEra,4, 19,EXCEEDS_PAD)
但是在解析时,得到的分析对象(在你的情况下,week
变量)与年创建场 - 因为你可以通过看值:
{ = 2017年一年,...
格式化设置与年的时代场。因此,当您尝试格式化week
时,它会尝试从week
变量中获取此字段。由于此字段不存在(week
仅包含年,而不是年代),它会抛出UnsupportedTemporalTypeException
。
的解决方案是使用年字段(u
模式)在格式化:
val df = DateTimeFormatter.ofPattern("uuuu_'w'w")
println(df)
val week = df.parse("2017_w19")
println(week)
println(df.format(week))
输出将是:
值(年,4,19 ,EXCEEDS_PAD)'_''w'Localized(WeekOfWeekBasedYear,1)
{年 = 2017,WeekOfWeekBasedYear [WeekFields [SUNDAY,1] ] = 19},ISO
2017_w19
注意,现在的格式是用年场创建,并format
方法现在试图从分析的对象得到这个领域,并不会引发任何异常。
伟大的工作雨果!我很喜欢这个。 – Synesso
对于我来说,你不能使用DateTimeFormatter来格式化一个TemporalAccessor,它是一个过于宽泛的时间接口。尝试先将它转换为DateTime对象。
那是什么语言? Scala呢? (并不是说这对您的问题确实很重要,对于Java工程师来说,这只是一个棘手的问题。)如果您没有得到有用的答案,可以将它翻译成Java以便覆盖更广泛的读者。 –