Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 939
goe Avatar asked Aug 30 '13 13:08

goe


1 Answers

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");             } 
like image 91
Sajal Dutta Avatar answered Oct 01 '22 19:10

Sajal Dutta