dao hodac dao hodac - 1 year ago 164
Java Question

apache DateUtils: parsing a date with multiple patterns

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

. It seems to use the first parser, even if it should detect the difference between

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",

//returns Tue Apr 05 12:34:22 CET 29 which is wrong


Answer Source

You should use 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.


   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",

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download