0

I'm parsing user date of birth string. And faced a very strange parsing scenario.

My code is the following:

SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy")
try {
  Date date = formatter.parse(input); // input - is a user entered string
} catch (ParseException e) {
}

If input is "22221985", I have a date 22, October, 1986. But I expect some sort of ParseException for this and similar scenario, when month is higher, then 12.

  • There will be no parse exceptions because this is how Calendar works in Java. – Simon Martinelli Dec 19 '22 at 16:48
  • 2
    You are using terrible date-time classes that were years ago supplanted by the modern *java.time* classes defined in JSR 310. – Basil Bourque Dec 19 '22 at 17:20
  • 2
    I strongly recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 19 '22 at 19:23
  • 1
    You will want `LocalDate.parse("22221985", DateTimeFormatter.ofPattern("ddMMuuuu").withResolverStyle(ResolverStyle.STRICT))`. It throws `java.time.format.DateTimeParseException: Text '22221985' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 22`. And enjoy how precise and informative the exception message is. – Ole V.V. Dec 19 '22 at 19:51

0 Answers0