DateTimeFormatter automatically corrects invalid (syntactically possible) calendar date
Java DateTimeFormatter
throws an exception if you try to execute a date that is out of range, for example:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");
String dateString = "12/32/2015";
LocalDate ld = LocalDate.parse(dateString, dtf);
will throw:
Exception in thread "main" java.time.format.DateTimeParseException: Text '12/32/2015' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32
But when I enter an invalid calendar date, which is still syntactically possible by their standards, it automatically detects it as a valid date, for example:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");
String dateString = "2/31/2015";
LocalDate ld = LocalDate.parse(dateString, dtf);
it parses successfully, but auto-validates 2015-02-28
. I don't want this behavior, I want it to still throw an exception when the date is not a valid calendar date. Is there a built-in option I can set to do this, or do I really need to try to manually filter these instances?
source to share
You can use recognizer style STRICT
:
import static java.time.format.ResolverStyle.STRICT;
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uuuu").withResolverStyle(STRICT);
The default ofPattern
uses a SMART
style recognizer that will use sensible defaults.
Please note: I used uuuu
instead yyyy
, i.e. YEAR instead of YEAR_OF_ERA . Assuming you are in the Gregorian calendar system, they are equivalent to years in the current era (year 1 or more). The difference is explained in more detail in the links above.
source to share