Reputation: 7824
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?
Upvotes: 2
Views: 1528
Reputation: 44071
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).
Upvotes: 3