I need to parse a string into a LocalDate
. The string looks like 31.* 03 2016
in regex terms (i.e. .*
means that there may be 0 or more unknown characters after the day number).
Example input/output: 31xy 03 2016
==> 2016-03-31
I was hoping to find a wildcard syntax in the DateTimeFormatter documentation to allow a pattern such as:
LocalDate.parse("31xy 03 2016", DateTimeFormatter.ofPattern("dd[.*] MM yyyy"));
but I could not find anything.
Is there a simple way to express optional unknown characters with a DateTimeFormatter
?
ps: I can obviously modify the string before parsing it but that's not what I'm asking for.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
DateTimeFormatter is immutable and thread-safe. DateTimeFormatter formats a date-time using user defined format such as "yyyy-MMM-dd hh:mm:ss" or using predefined constants such as ISO_LOCAL_DATE_TIME. A DateTimeFormatter can be created with desired Locale, Chronology, ZoneId, and DecimalStyle.
static DateTimeFormatter. ISO_DATE_TIME. The ISO-like date-time formatter that formats or parses a date-time with the offset and zone if available, such as '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
format. DateTimeFormatterBuilder Class in Java. DateTimeFormatterBuilder Class is a builder class that is used to create date-time formatters. DateTimeFormatter is used as a Formatter for printing and parsing date-time objects.
I’d do it in two steps, use a regexp to get the original string into something that LocalDate can parse, for example:
String dateSource = "31xy 03 2016";
String normalizedDate = dateSource.replaceFirst("^(\\d+).*? (\\d+ \\d+)", "$1 $2");
LocalDate date = LocalDate.parse(normalizedDate, DateTimeFormatter.ofPattern("dd MM yyyy"));
System.out.println(date);
I know it’s not what you asked for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With