Search code examples
javaapache-commons-dateutils

date format using apache lang DateUtil fails


i was trying to convert date in string format to date using DateUtils. Following are my expected date format,

private static final String[] EXPECTED_DATE_FORMAT = {"yyyy-MM-dd","dd-MM-yyyy","dd-MMM-yyyy",};

And I ran the test against following values,

System.out.println(org.apache.commons.lang.time.DateUtils.parseDate("2019-05-18", EXPECTED_DATE_FORMAT));
System.out.println(org.apache.commons.lang.time.DateUtils.parseDate("18-05-2019", EXPECTED_DATE_FORMAT));
System.out.println(org.apache.commons.lang.time.DateUtils.parseDate("18-May-2019", EXPECTED_DATE_FORMAT));

And I am getting the following result,

Sat May 18 00:00:00 IST 2019
Tue Nov 09 00:00:00 IST 23
Sat May 18 00:00:00 IST 2019

Why the second value "18-05-2019" is not matching with the format "dd-MM-yyyy" and get me the same result? What changes I should support both dd-MM-yyyy and yyyy-MM-dd ?


Solution

  • This is caused by the fact that DateUtils.parseDate internally uses a SimpleDateFormat with "lenient parsing" (SimpleDateFormat.setLenient(true)). Lenient parsing means, roughly, that if the string does not match exactly the pattern, the parser tries to "guess" heuristically how to interpret your string to get some meaningful date. In your example, the second string fails because the first pattern is considered "good enough" to be used, and then the parser messes things up.

    You can use DateUtils.parseDateStrictly to disable leniency.