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