I have the following lines:
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = simpleDateFormat.parse("2004-52-05");
I expect that an exception will be thrown in line 2, because '52' is not a valid month, but code runs and the date stored in d object is
Sat Apr 05 00:00:00 EEST 2008
Can somebody explain me why?
If you want to create a date object that strictly matches your pattern, then set lenient to false.
From Javadoc
Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.
Refer this for more information lenitent
So add this..
simpleDateFormat.setLenient(false);
This will throw an Exception
as you were Expecting..
java.text.ParseException: Unparseable date: "2004-52-05"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With