2

I'm using ThreeTenABP and seem to have run into a difference of implementation between LocalDate.parse(String) and LocalDate.parse(String, DateTimeFormatter).

LocalDate.parse("31/02/1985", DateTimeFormatter.ofPattern("dd/MM/yyyy"))

Parses to "1985-02-28" without throwing an exception.

LocalDate.parse("2015-02-31")

DateTimeParseException: Text '2015-02-31' could not be parsed: Invalid date 'FEBRUARY 31'

The documentation almost implies this with "The string must represent a valid date" only mentioned with the formatter-less method.

How can I validate a date in a custom format like 31/02/1985 using threeten bp?

Tom
  • 6,946
  • 2
  • 47
  • 63
  • For others going down this same rabbit hole as I - see this for custom formats containing years and strict resolving - http://stackoverflow.com/questions/26393594/using-new-java-8-datetimeformatter-to-do-strict-date-parsing – Tom Sep 29 '15 at 20:14

1 Answers1

3

The main difference can be explained by the fact that the ISO_LOCAL_DATE-formatter is strict by default. Other formatters are smart by default. The full sentence you cited reads like this:

The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.

So it is pretty clear that the formatter-less method can only parse ISO-compatible dates in strict mode, and even then only a subset of ISO-8601, namely:

uuuu-MM-dd or uuuuMMdd

About the strict mode, you can see it studying the source code:

   public static final DateTimeFormatter ISO_LOCAL_DATE; 
   static { 
     ISO_LOCAL_DATE = new DateTimeFormatterBuilder() 
       .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) 
       .appendLiteral('-') 
       .appendValue(MONTH_OF_YEAR, 2) 
       .appendLiteral('-') 
       .appendValue(DAY_OF_MONTH, 2) 
       .toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); 
     } 

However, the strict mode does not seem to be well documented. Anyway, if you want to realize the strict mode with a custom formatter then simply call its method withResolverStyle(ResolverStyle.STRICT).

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Yay! `DateTimeParseException: Text '31/02/1985' could not be parsed`. Of course now it can't actually parse valid dates, but that's another problem. Thank you. :) – Tom Sep 29 '15 at 01:23