views:

32

answers:

1

I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.

here are the formats: 9/09 9/2009 09/2009 9/1/2009 9-1-2009

What is the best way to go about trying to parse all of these? These seem to be the most common, but I guess what is hanging me up is that if i have a pattern of "M/yyyy" wont that always catch before "MM/yyyy" Do I have to set up my try/catch blocks nested in a least restrictive to most restrictive way? it seems like it sure is going to take a lot of code duplication to get this right.

+1  A: 

You'll need to use a different SimpleDateFormat object for each different pattern. That said, you don't need that many different ones, thanks to this:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

So, you'll need these formats:

  • "M/y" (that covers 9/09, 9/2009, and 09/2009)
  • "M/d/y" (that covers 9/1/2009)
  • "M-d-y" (that covers 9-1-2009)

So, my advice would be to write a method that works something like this (untested):

...
String[] formatStrings = {"M/y", "M/d/y", "M-d-y"};
...

Date tryParse(String dateString)
{
    Date d = null;

    for (String formatString : formatStrings)
    {
        try
        {
            d = new SimpleDateFormat(formatString).parse(dateString);
            break;
        }
        catch (ParseException e) {}
    }

    return d;
}
Matt Ball