0

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

rawi
  • 521
  • 3
  • 13

1 Answers1

2

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);
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
  • Thanks Mikko. Yes, it's working correct this way. Please could you explain, why the method .parseStrict() didn't help? I thought it would tell the DateTimeFormatterBuilder to do just that. – rawi Nov 24 '17 at 09:32
  • 1
    .parseStrict() doesn't work because toFormatter() ignores previous set values and uses his own (SMART). – Knoobie Aug 15 '18 at 10:12