My program is parsing an input string to a LocalDate
object. For most of the time the string looks like 30.03.2014
, but occasionally it looks like 3/30/2014
. Depending on which, I need to use a different pattern to call DateTimeFormatter.ofPattern(String pattern)
with. Basically, I need to check if the string matches the pattern dd.MM.yyyy
or M/dd/yyyy
before doing the parsing.
The regex approach would be something like:
LocalDate date;
if (dateString.matches("^\\d?\\d/\\d{2}/\\d{4}$")) {
date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("M/dd/yyyy"));
} else {
date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd.MM.yyyy"));
}
This works, but it would be nice to use the date pattern string when matching the string also.
Are there any standard ways to do this with the new Java 8 time API, without resorting to regex matching? I have looked in the docs for DateTimeFormatter
but I couldn't find anything.
replace("//", ".")
? – AbramsSimpleDateFormat
cannot directly parse to aLocalDate
, only tojava.util.Date
which is quite different. – Pollard