DateFormat#parse does not necessarily use the entire string:
Parses text from the beginning of a given line to create a date. The method may not use all the text in a given string.
(my emphasis)
SimpleDateFormat docs tell us that yyyy does not necessarily mean that it will take four digits during the year:
Year:
...
- For parsing, if the number of letters in the pattern is more than 2, the year is interpreted literally, regardless of the number of digits. Thus, using the template
"MM/dd/yyyy" , "01/11/12" analyzes until 12 January 12 AD
So, it is correct (if possible, surprising) that he parses this line in the year 201.
You can use parse(String,ParsePosition) to find out if the entire string has been consumed, or check it with a regular expression before parsing. Here's a version that will verify that the entire string has been parsed, not just the first characters:
public static boolean isThisDateValid(String dateToValidate, String dateFormat) { if (dateToValidate == null) { return false; } SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); sdf.setLenient(false); ParsePosition position = new ParsePosition(0); Date date = sdf.parse(dateToValidate, position); return date != null && position.getIndex() == dateToValidate.length(); }
source share