Parsing Dates in Varied Formats with SimpleDateFormat
When parsing dates from user input, it's common to encounter varying formats. Handling these variations can be challenging, especially considering the precedence rules of SimpleDateFormat.
To address this, use separate SimpleDateFormat objects for each unique format. Although this may seem to require excessive code duplication, the flexibility of SimpleDateFormat's number formatting rules allows for a more concise approach.
For instance, consider the following date formats:
These can be grouped into three categories:
The following method exemplifies the implementation:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; public class DateParser { private static List<String> FORMAT_STRINGS = Arrays.asList("M/y", "M/d/y", "M-d-y"); public static Date parse(String dateString) { for (String formatString : FORMAT_STRINGS) { try { return new SimpleDateFormat(formatString).parse(dateString); } catch (ParseException e) { // Ignore parse exceptions and continue to the next format } } return null; // If no formats match, return null } }
In this way, you can handle a range of date formats without the need for excessive nested try/catch blocks or code duplication.
The above is the detailed content of How Can I Efficiently Parse Dates with Multiple Formats Using SimpleDateFormat?. For more information, please follow other related articles on the PHP Chinese website!