Search code examples
java-8datetime-formatgroovy-console

DateTimeFormatterBuilder parsing days below 31 SMART not STRICT if appendValueReduced is used


Playing in groovyConsole with DateTimeFormatter and DateTimeFormatterBuilder

String inputDateString = "31.2.58" // german date format

dtfIn = DateTimeFormatter
        .ofPattern ( "d.M.uu" )
        .withResolverStyle ( ResolverStyle.STRICT )

dtfIn.parse(inputDateString) // ERROR as expected

...but

// with base range 1937-2034
dtfIn = new DateTimeFormatterBuilder()
       .appendPattern("d.M.")
       .appendValueReduced(ChronoField.YEAR, 2, 2, Year.now().getValue() - 80)
       .parseStrict()
       .toFormatter()

dtfIn.parse(inputDateString) // Result: 1958-02-28

So DateTimeFormatterBuilder with .parseStrict() would parse rather SMART, which DateTimeFormatterBuilder shouldn't do at all but either STRICT or LENIENT (?)'

With day numbers over 31 I'll get an error.

The problem seem to be .appendValueReduced(). Without it I'd become an error as expected.

What do I do wrong?

Thanks

Rawi


Solution

  • DateTimeFormatter from DateTimeFormatterBuilder.toFormatter() is indeed SMART as documented:

    The resolver style will be SMART

    To obtain STRICT one has to use DateFormatter.withResolverStyle(ResolverStyle) in this case as follows:

    .toFormatter().withResolverStyle(ResolverStyle.STRICT);