Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard in DateTimeFormatter

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.

like image 982
assylias Avatar asked Mar 17 '16 14:03

assylias


People also ask

What is the difference between DateTimeFormatter and SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is DateTimeFormatter thread-safe?

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.

What is DateTimeFormatter Iso_date_time?

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]'.

What is the Java time format DateTimeFormatter?

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.


1 Answers

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.

like image 118
Ole V.V. Avatar answered Oct 06 '22 19:10

Ole V.V.