简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM