Search code examples
javadatetime-formatsimpledateformat

Is this a bug in SimpleDateFormat, or a feature?


I recently changed... continents and temporarily forgot to signify July 27th 2023 in the European way, i.e "27/07/2023", and instead maintained the American - style literal "07/27/2023", which I promptly passed as argument to the parse method of a SimpleDateFormat instance initialized with the European pattern "dd/MM/yyyy". I would have expected a ParseException to arise since there are only 12 months in the year, but the following runs fine:

System.out.println(new SimpleDateFormat("dd/MM/yyyy").parse("07/27/2023"));

and outputs

Fri Mar 07 00:00:00 EET 2025

I'm running corretto-17.0.2 JDK.

I understand why this happens mathematically (27 = 2 * 12 + 3 and it's March of 2023 + 2 = 2025, yay!) and I also understand that SimpleDateFormat has problems of its own, e.g thread (un)safety, but I was wondering whether this is something that could be reported as a bug, or whether there is some logic behind it that I don't understand. The official Oracle docs DON'T stipulate SimpleDateFormat::parse() as deprecated or considered for removal. Appreciate any input.


Solution

  • As mentioned by the comments, if you follow the documentation of parse(String) to the (linked) parse(String, ParsePosition), you find out that you can adjust the "leniency" of the parsing, and, if you set it to strict, as the following code does, a ParseException is thrown in this case.

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setLenient(false);
    System.out.println(sdf.parse("07/27/2023"));