Java DateTimeFormatter
throws an exception for when you try a date that goes outside of a possible 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 that is still syntactically possible by their standards, it autocorrects it to be a valid date, for example:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");
String dateString = "2/31/2015";
LocalDate ld = LocalDate.parse(dateString, dtf);
it successfully parses but autocorrects to 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 for that to happen, or do I really have to try to manually sift out these instances?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…