I want to parse custom multiple Date formats in Java. Here is my code
Scenario 1: Order of patterns:
- yyMMdd'h'HH
- yyMMdd
DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendOptional(DateTimeFormatter.ofPattern("yyMMdd'h'HH")) .appendOptional(DateTimeFormatter.ofPattern("yyMMdd")).toFormatter();
Works:
String dateString1 = "201028h05";
LocalDateTime date1 = LocalDateTime.parse(dateString1, formatter);
Doesn't works:
String dateString2 = "201028";
LocalDateTime date1 = LocalDateTime.parse(dateString2, formatter);
Scenario 2: Order of patterns:
- yyMMdd
- yyMMdd'h'HH
DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendOptional(DateTimeFormatter.ofPattern("yyMMdd")).toFormatter(); .appendOptional(DateTimeFormatter.ofPattern("yyMMdd'h'HH"))
Doesn't Work:
String dateString1 = "201028h05";
LocalDateTime date1 = LocalDateTime.parse(dateString1, formatter);
Works:
String dateString2 = "201028";
LocalDateTime date1 = LocalDateTime.parse(dateString2, formatter);
How to make it work for both of the date patterns irrespective of any input pattern order. I don't want to use any external dependency for this.
dateString1
does not match the patternyyMMdd'h'HH
, since it is missing the whole'h'HH
component. You would need to add something of the sorth00
to the seconddateString1
for it to be captured by the first pattern. – Barcus