具有指定的parseDefaulting的DateTimeFormatterBuilder与YEAR字段冲突 [英] DateTimeFormatterBuilder with specified parseDefaulting conflicts for YEAR field
问题描述
我有以下格式化程序:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyyMM")
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.YEAR, ZonedDateTime.now().getYear())
.toFormatter()
.withZone(ZoneId.systemDefault());
我尝试解析字符串201505
I try to parse the string "201505"
System.out.println(ZonedDateTime.parse("201505", formatter));
并抛出异常:
引起:java.time.DateTimeException:发现冲突:2016年
与2015年不同
Caused by: java.time.DateTimeException: Conflict found: Year 2016 differs from Year 2015
如果我注释掉YEAR默认值的设置,它就有效。
It works if I comment out the setting of default value for YEAR.
据我所知文档,它只应该尝试替换默认值没有解析值。这似乎适用于月份,因为我的月份不同于解析的默认月份。但它不适用于一年。
As far as I understood the documentation, it should only try to replace the default value if there is no value parsed. Seems like this works for month as I have different month than the default one parsed. However it doesn't work for year.
如果我错误地使用它,有人会告诉我是否有不同的方法来定义模式中可能不存在的字段的默认值?
Am I using it wrong could someone tell me if there is a different way to define default values for fields that might not be present in a pattern?
推荐答案
问题是模式字母y是指 ChronoField.YEAR_OF_ERA
,而不是 ChronoField.YEAR
。只需更改最后一个 parseDefaulting
行:
The problem is that the pattern letter "y" refers to ChronoField.YEAR_OF_ERA
, not ChronoField.YEAR
. Simply change the last parseDefaulting
line:
.parseDefaulting(ChronoField.YEAR_OF_ERA, ZonedDateTime.now().getYear())
它应该有效。
这篇关于具有指定的parseDefaulting的DateTimeFormatterBuilder与YEAR字段冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!