Search code examples
javaparsingdatetimesimpledateformat

How to parse dates in multiple formats using SimpleDateFormat


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.


Solution

  • 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):

    // ...
    List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
    // ...
    
    Date tryParse(String dateString)
    {
        for (String formatString : formatStrings)
        {
            try
            {
                return new SimpleDateFormat(formatString).parse(dateString);
            }
            catch (ParseException e) {}
        }
    
        return null;
    }