DateTimeFormatterBuilder with specified parseDefaulting conflicts for YEAR field

心不动则不痛 提交于 2019-12-05 17:15:51

问题


I have the following formatter:

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());

I try to parse the string "201505"

System.out.println(ZonedDateTime.parse("201505", formatter));

and it throws an exception:

Caused by: java.time.DateTimeException: Conflict found: Year 2016 differs from Year 2015

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?


回答1:


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())

and it should work.



来源:https://stackoverflow.com/questions/38307816/datetimeformatterbuilder-with-specified-parsedefaulting-conflicts-for-year-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!