Saturday, March 1, 2008

SimpleDateFormat is lenient

Today i discovered something about SimpleDateFormat, a Java Date Formatter API.

I used a statement like,
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

In my unit test i wanted a failing test when i pass in a String "13/01/2008". The method
df.parse()
has a ParseException in its throws clause. I was hoping that, that exception will be thrown when this invalid date was passed in..

Instead it parsed it as January 1 2009.

When i did some digging around, i realised that there was a method called setLenient.

Once i made a call df.setLenient(false), prior to the parse call, it threw the ParseException when invalid date was passed in..

I found it a little weird and would have expected setLenient to be set to false by default.

No comments: