Unexacte parsing in SimpleDateFormat

How to parse a string with always different formats of date (sometimes "yyyy-MM-dd HH:mm:ss", or "yyyy-MM-dd'T'HH:mm" or also "yyyy-MM-dd HH:mm")?

If I use the following code - it fails if the string in value has other format than "yyyy-MM-dd HH:mm"

public static Date test(String value) throws ... {

  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  return df.parse(value);


}
Jon Skeet
people
quotationmark

I would suggest you just try to parse each specific format, catching ParseException and just moving onto the next format:

private static final String[] patterns = {
    "yyyy-MM-dd HH:mm",
    "yyyy-MM-dd'T'HH:mm",
    "yyyy-MM-dd HH:mm"
};

public static Date test(String value) throws ... {
    for (String pattern : patterns) {
        try {
           DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
           return df.parse(value);
        } catch (ParseException e) {
           // No-op - move onto the next pattern
        }
    }
    // Do whatever you want here - throw ParseException, or return null
}

That's simple, but abuses exceptions. You could use the more obscure parse(String, ParsePosition) call instead:

public static Date test(String value) throws ... {
    for (String pattern : patterns) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = df.parse(value, new ParsePosition(0));
        if (date != null) {
            return date;
        }
    }
    // Do whatever you want here - throw ParseException, or return null
}

That may perform better - you'd have to benchmark it to say for sure.

It's unfortunate that you have to recreate the SimpleDateFormat objects on each call, but that's an issue with it not being thread-safe. Another alternative is to use Joda Time - which is a much nicer API overall - but it's not very clear how you'd do the exception-free approach there. (It may well be possible, just a bit obscure again. I suspect that DateTimeFormatter.parseInto would be your friend here.)

people

See more on this question at Stackoverflow