How to parse dates in multiple formats using SimpleDateFormat

前端 未结 12 1660
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 08:41

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 for

12条回答
  •  独厮守ぢ
    2020-11-22 09:21

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

提交回复
热议问题