↓ Skip to main content

How to correctly parse dates in Java

·117 words·1 min
Sergii Zolotarov
Author
Sergii Zolotarov
Twenty years of Java, from Kyiv to Leeuwarden. Currently at Booking.com

I have noticed long ago that SimpleDateFormat parses dates rather funny, for example 18/18/1908 when parsed using this pattern MM/dd/yyyy will be converted to date: 06/18/1909. This is 100% legal from the DateFormat point of view - day overflow will roll the month one point up, and month overflow rolls the year. This is ok for computer sense, however this is against common sense of a human.

How do we override this? Set the lenient flag to false, this will enforce stricter rules for date validation - there will never be a 18 month in a GregorianCalendar:


      SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
      format.setLenient(false);
      Date date = format.parse(date);
      ....

First published on the old anydoby.com blog on 2008-03-20.