Little strokes fell great oaks. We have a similar saying in Romanian and I remembered it after I saw that this code

does not complain and displays

The explanation is simple and is caused by a small detail in SimpleDateFormat api that is setting lenient field:

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object’s format. With strict parsing, inputs must match this object’s format.
This method is equivalent to the following call.

This leniency value is overwritten by a call to setCalendar().

If the purpose of above code is to validate the date, setting the lenient field to false

fixes the problem

It’s very easy to miss this kind of problems especially if a code like this is hidden in some useful methods somewhere in a common project. The solution to avoid these issues is simple but often overlooked. All we need is to add unit tests and even if we miss some detail from api, a failed test will force us to read it again.

This site uses Akismet to reduce spam. Learn how your comment data is processed.