Home > Java > javaTutorial > How Can I Parse Variable Date Formats (e.g., 9/09, 9/1/2009, 9-1-2009) Efficiently in Java?

How Can I Parse Variable Date Formats (e.g., 9/09, 9/1/2009, 9-1-2009) Efficiently in Java?

Patricia Arquette
Release: 2024-12-12 18:53:10
Original
580 people have browsed it

How Can I Parse Variable Date Formats (e.g., 9/09, 9/1/2009, 9-1-2009) Efficiently in Java?

Parsing Variable Date Formats with SimpleDateFormat

When facing a scenario where dates are entered in inconsistent formats, SimpleDateFormat can be utilized for efficient parsing.

To accommodate the given formats:

  • 9/09, 9/2009, 09/2009: A pattern of "M/y" captures these variations, where "M" represents the month and "y" the year.
  • 9/1/2009: For dates with a day component, a pattern of "M/d/y" should be used, where "d" additionally represents the day.
  • 9-1-2009: A similar pattern, "M-d-y", is appropriate for dates using a hyphen as the delimiter.

It's not necessary to nest try/catch blocks. Instead, iterate over multiple SimpleDateFormat objects with varying patterns.

A method like the following can be implemented:

// ...
List<String> formatStrings = List.of("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 ignored) {}
    }
    return null;
}
Copy after login

The above is the detailed content of How Can I Parse Variable Date Formats (e.g., 9/09, 9/1/2009, 9-1-2009) Efficiently in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template