How to parse dates in multiple formats using SimpleDateFormat

前端 未结 12 1506
伪装坚强ぢ
伪装坚强ぢ 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:15

    What about just defining multiple patterns? They might come from a config file containing known patterns, hard coded it reads like:

    List knownPatterns = new ArrayList();
    knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
    knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss'Z'"));
    knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
    knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss"));
    knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"));
    
    for (SimpleDateFormat pattern : knownPatterns) {
        try {
            // Take a try
            return new Date(pattern.parse(candidate).getTime());
    
        } catch (ParseException pe) {
            // Loop on
        }
    }
    System.err.println("No known Date format found: " + candidate);
    return null;
    

提交回复
热议问题