Friday, October 14, 2011

Interesting SimpleDateFormat Problem

We wasted around half an hour today on a trivial SimpleDateFormat issue today. We wanted to validate a date and used the below code.

@Test
public void testShouldThrowTheException() {
String formatStr = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(formatStr);
try {
df.parse("2011-15-05");
Assert.fail("It should not come here");
} catch (ParseException e) {
e.printStackTrace();
}
}

Surprisingly our testcase was failing and did not know why. SimpleDateFormat was returning 2012 March 5th and I was so annoyed :S..

Looks like the SimpleDateFormat will not validate the correctness untill you set the lenient to false.

@Test
public void testShouldThrowTheException() {
String formatStr = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(formatStr);
df.setLenient(false);
try {
df.parse("2011-24-05");
Assert.fail("failed");
} catch (ParseException e) {
e.printStackTrace();
}
}

This works perfectly fine. Simple problem but easy to overlook.

Enjoy
Manisha

No comments:

Post a Comment