public void parsedate(String date) {
DateTimeFormatter formatter = null;
formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("yyyyMMdd"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.appendOptional(DateTimeFormatter.ofPattern("MM/dd/yyyy")).toFormatter();
TemporalAccessor parse = formatter.parse(date);
System.out.println("original" + date);
return LocalDateTime.parse(date, formatter);
}
String[] strDates = new String[]{
"20180429",
"2018-04-29",
"04/29/2018",
"01/20/1999",
"1899-12-25",
"2020-02-29", // leap year future
"00010101",
"19160229" // leap year past
};
for(String date: strDates) {
parsedate(date);
}
I am parsing dates with multiple date patterns. I will pass the date string to parsedate method. My date string is parsed. But I want to get the pattern of the date which is parsed.
Example:
Input date: "2018-04-29" Process: parsedate("2018-04-29") Output: date parsed successfully
My expectation is get the pattern as "yyyy-MM-dd" for Input date: "2018-04-29". How to get it?
After looking at the documentation, there seems to be no way to see which of the optional formats succeeded. So the easy way out is to build a collection of formatters to try, and to use them in order until one succeeds. However, this is ugly: you are using exceptions for flow-control
An existing question on SO deals with this problem. My suggested answer goes along the lines of one of its answers.
A cleaner option may be to use your formats both as regular expressions (to only examine likely candidates) and as actual date formats (to parse only the good candidates). This comes at a cost in readability, and will still throw exceptions when parsing ambiguous formats, because the format-to-regex code is very simplistic:
The initial code could now be written as:
Before complicating this further, I would probably just go with ugly exceptions-as-control-flow (1st code snippet) as a lesser evil to re-implementing a time-parsing library.
disclaimer: above code is un-tested and may not compile and/or perform as expected