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?

1
  • For others going down this same rabbit hole as I - see this for custom formats containing years and strict resolving - stackoverflow.com/questions/26393594/… Commented Sep 29, 2015 at 20:14

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

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. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.