0

I'm wanting to create a LocalDate instance by parsing a String with a DateTimeFormatter, I noticed that if I parse a string where the day is greater than the number of days in the month then the smart resolver just resolves it to the last day for example. (I want the exception to be thrown)

    DateTimeFormatter smartFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    
    LocalDate.parse("20000431", smartFormatter);

This is resolved to 30th April 2000, so I added the following

    DateTimeFormatter strictFormatter = DateTimeFormatter.ofPattern("yyyyMMdd").withResolverStyle(ResolverStyle.STRICT);
    
    LocalDate.parse("20000431", strictFormatter);

As expected this now throws an exception. However, I've noticed that it also throws an exception for the 30th April, which is obviously valid. What's wrong with the below?

    DateTimeFormatter strictFormatter = DateTimeFormatter.ofPattern("yyyyMMdd").withResolverStyle(ResolverStyle.STRICT);
    
    LocalDate.parse("20000430", strictFormatter);
PDStat
  • 5,513
  • 10
  • 51
  • 86

1 Answers1

4

That's because yyyy means year-of-era. STRICTly speaking, such date probably expects "AD" or "BC" to be present.

If you change the pattern string to

uuuuMMdd

it'll work.

Despite the fact that yyyy looks like a natural way to express "the current year", it does not actually mean "the current year", but rather "the current year in the current era".

You should always use uuuu instead of yyyy.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130