SimpleDateFormat is not working properly

I am trying to use this function, but it does not work with this '12 / 05 / 201a 'case, does anyone know why this is happening?

In my test, I use this System.out.println(isThisDateValid("12/05/201a", "dd/MM/yyyy")); , and the answer was true , but I expect the result to be false, because the year contains letters.

  public static boolean isThisDateValid(String dateToValidate, String dateFromat) { if (dateToValidate == null) { return false; } SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); try { //if not valid, it will throw ParseException Date date = sdf.parse(dateToValidate); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); return false; } return true; } 
+5
source share
1 answer

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(); } 
+12
source

All Articles