Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat behaviour

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?

like image 729
lucian.marcuta Avatar asked Jan 08 '23 01:01

lucian.marcuta


1 Answers

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"
like image 70
Hiren Avatar answered Jan 14 '23 18:01

Hiren