How to Apply Multiple Date Formats to DateTimeFormatter in Java
We can apply multiple date formats to a DateTimeFormatter
using optional sections.
Suppose we’re working with the following date formatter.
DateTimeFormatter formatter1 = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss");
We want to include a formatter that can parse a different date format, which might look something like this:
DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("ddMMMyyyy:HH:mm:ss.SSS");
1. Entirely different date formats
We can use the optional sections pattern to create multiple optional sections, each delimited by square brackets []
.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("[yyyy-MM-dd HH:mm:ss][ddMMMyyyy:HH:mm:ss.SSS]");
This method allows for entire sections of the parsed string (i.e. that enclosed in the brackets []
) to be missing.
LocalDateTime.parse("2022-07-14 03:00:00", formatter)
LocalDateTime.parse("14Jul2022:03:00:00.123", formatter)
2. Mildly different date formats
If only a subsection of the format string will be different, we can use the optional section for a substring of the date format.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss[.SSSSSSSSS][.SSS]");
The above DateTimeFormatter
will match second, millisecond, and nanosecond timestamps.
LocalDateTime.parse("2022-07-14 03:00:00", formatter)
LocalDateTime.parse("2022-07-14 03:00:00.123", formatter)
LocalDateTime.parse("2022-07-14 03:00:00.123456789", formatter)