dao hodac dao hodac - 3 months ago 8
Java Question

apache DateUtils: parsing a date with multiple patterns

I want to parse a date that has different potential formats using

DateUtils.parseDate
. It seems to use the first parser, even if it should detect the difference between
23/10/2014
and
2014/10/23
.

It actually parses the date even if it is wrong, so that I can't even catch an exception. How can I do? Is it a bug? (commons-lang3-3.3.2)

Here is a code snippet

package snippet;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;

public class TestDateFormat {

public static void main(String[] args) throws ParseException {

Date d = DateUtils.parseDate("23/10/2014T12:34:22",
new String[] {"yyyy/MM/dd'T'HH:mm:ss",
"dd/MM/yyyy'T'HH:mm:ss"});

System.out.println(d);
//returns Tue Apr 05 12:34:22 CET 29 which is wrong
}

}

Answer

You should use DateUtils.parseDateStrictly:

DateUtils#parseDateStrictly

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.

The parser parses strictly - it does not allow for dates such as "February 942, 1996".

Internally, what it does is setting to false the lenient attribute of the DateFormat used: DateFormat.html#setLenient

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

Example:

   public static void main(String[] args) throws ParseException {
      Date d = DateUtils.parseDateStrictly("23/10/2014T12:34:22", 
          new String[] {"yyyy/MM/dd'T'HH:mm:ss",
              "dd/MM/yyyy'T'HH:mm:ss"});

      System.out.println(d);
  }
Comments