Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatterBuilder with specified parseDefaulting conflicts for YEAR field

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?

like image 676
Ivelina Georgieva Avatar asked Jul 11 '16 13:07

Ivelina Georgieva


1 Answers

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.

like image 161
JodaStephen Avatar answered Nov 07 '22 16:11

JodaStephen