I need to parse date-times as strings coming as two different formats:
The following dateTimeFormatter pattern properly parses the first kind of date strings
DateTimeFormatter.ofPattern ("uuuuMMddHHmmss[,S][.S]X")
but fails on the second one as dashes, colons and T are not expected.
My attempt was to use optional sections as follows:
DateTimeFormatter.ofPattern ("uuuu[-]MM[-]dd['T']HH[:]mm[:]ss[,S][.S]X")
Unexpectedly, this parses the second kind of date strings (the one with dashes), but not the first kind, throwing a
java.time.format.DateTimeParseException: Text '19861221235959Z' could not be parsed at index 0
It's as if optional sections are not being evaluated as optional...
A formatter created from a pattern can be used as many times as necessary, it is immutable and is thread-safe.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
DateTimeFormatter fmt = DateTimeFormatter. ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System. out. println(ldt.
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.
The problem is that your pattern is considering the entire string as the year. You can use .appendValue(ChronoField.YEAR, 4)
to limit it to four characters:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendPattern("[-]MM[-]dd['T']HH[:]mm[:]ss[,S][.S]X")
.toFormatter();
This parses correctly with both of your examples.
If you fancy being even more verbose, you could do:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.optionalStart().appendLiteral('-').optionalEnd()
.appendPattern("MM")
.optionalStart().appendLiteral('-').optionalEnd()
.appendPattern("dd")
.optionalStart().appendLiteral('T').optionalEnd()
.appendPattern("HH")
.optionalStart().appendLiteral(':').optionalEnd()
.appendPattern("mm")
.optionalStart().appendLiteral(':').optionalEnd()
.appendPattern("ss")
.optionalStart().appendPattern("X").optionalEnd()
.toFormatter();
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