问题
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.
回答1:
There is no direct support for this in java.time
.
The closest would be to use parse(CharSequence,ParsePosition) using two different formatters.
// create the formatter for the first half
DateTimeFormatter a = DateTimeFormatter.ofPattern("dd")
// setup a ParsePosition to keep track of where we are in the parse
ParsePosition pp = new ParsePosition();
// parse the date, which will update the index in the ParsePosition
String str = "31xy 03 2016";
int dom = a.parse(str, pp).get(DAY_OF_MONTH);
// some logic to skip the messy 'xy' part
// logic must update the ParsePosition to the start of the month section
pp.setIndex(???)
// use the parsed day-of-month in the formatter for the month and year
DateTimeFormatter b = DateTimeFormatter.ofPattern("MM yyyy")
.parseDefaulting(DAY_OF_MONTH, dom);
// parse the date, using the *same* ParsePosition
LocalDate date = b.parse(str, pp).query(LocalDate::from);
While the above is untested it should basically work. However, it would be far easier parse it manually.
回答2:
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.
来源:https://stackoverflow.com/questions/36063371/wildcard-in-datetimeformatter