How to parse dates in multiple formats using SimpleDateFormat

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

    For the modern answer I am ignoring the requirement to use SimpleDateFormat. While using this class for parsing was a good idea in 2010 when this question was asked, it is now long outdated. The replacement, DateTimeFormatter, came out in 2014. The idea in the following is pretty much the same as in the accepted answer.

    private static DateTimeFormatter[] parseFormatters = Stream.of("M/yy", "M/y", "M/d/y", "M-d-y")
            .map(DateTimeFormatter::ofPattern)
            .toArray(DateTimeFormatter[]::new);
    
    public static YearMonth parseYearMonth(String input) {
        for (DateTimeFormatter formatter : parseFormatters) {
            try {
                return YearMonth.parse(input, formatter);
            } catch (DateTimeParseException dtpe) {
                // ignore, try next format
            }
        }
        throw new IllegalArgumentException("Could not parse " + input);
    }
    

    This parses each of the input strings from the question into a year-month of 2009-09. It’s important to try the two-digit year first since "M/y" could also parse 9/09, but into 0009-09 instead.

    A limitation of the above code is it ignores the day-of-month from the strings that have one, like 9/1/2009. Maybe it’s OK as long as most formats have only month and year. To pick it up, we’d have to try LocalDate.parse() rather then YearMonth.parse() for the formats that include d in the pattern string. Surely it can be done.

提交回复
热议问题