Why SimpleDateFormat("MM/dd/yyyy") parses date to 10/20/20128?

goe picture goe · Aug 30, 2013 · Viewed 47.9k times · Source

I have this code:

  DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
  dateFormat.setLenient(false);
  Date date = dateFormat.parse("10/20/20128");

and I would expect the dateFormat.parse call to throw ParseException since the year I'm providing is 5 characters long instead of 4 like in the format I defined. But for some reason even with the lenient set to false this call returns a Date object of 10/20/20128.

Why is that? It doesn't make much sense to me. Is there another setting to make it even more strict?

Answer

Sajal Dutta picture Sajal Dutta · Aug 30, 2013

20128 is a valid year and Java hopes the world to live that long I guess.

if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits.

Reference.

If you want to validate if a date is in limit, you can define one and check-

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date maxDate = sdf.parse("01/01/2099");  // This is the limit

if(someDate.after(maxDate)){            
    System.out.println("Invalid date");            
}