Apache DateUtils: parsing date with multiple patterns

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

. The first parser seems to be used, even if it should detect the difference between 23/10/2014

and 2014/10/23

.

It actually parses the date even if it's wrong, so I can't even catch the exception. How can I do? This is mistake? (Ordinary-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
    }

}

      

+3


source to share


1 answer


You must use DateUtils.parseDateStrictly

:

DateUtils # parseDateStrictly

Parses a string representing a date, trying different parsers.

The parsing will process each parsing in turn. Parsing only counts if it parses the entire input string. If no parsing patterns match, a ParseException is thrown.

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

Internally, what it does is set to the false

attribute lenient

used DateFormat

: DateFormat.html # setLenient



Specify whether to mitigate date and time parsing. With soft parsing, the parser can use heuristics to interpret inputs that do not exactly match this object. With strict parsing, Inputs must match this object.

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);
  }

      

+3


source







All Articles