You can create a DateTimeFormatter with multiple patterns using the DateTimeFormatterBuilder, but LocalDate.parse doesn't seem to like it. It works with a single pattern and fails with mutliple ones.
test("can parse dates") {
val formatter =
DateTimeFormatterBuilder()
.appendPattern("dd/MM/yy")
.appendPattern("dd/MM/yyyy") // <-- fine when commented out
.appendPattern("yyyy/MM/dd") // <-- fine when commented out
.toFormatter()
// error: Text '12/12/21' could not be parsed at index 8
LocalDate.parse("12/12/21", formatter) shouldBe LocalDate.of(2021, 12, 12)
// works just fine
LocalDate.parse("12/12/21", DateTimeFormatter.ofPattern("dd/MM/yy")) shouldBe LocalDate.of(2021, 12, 12)
}
Is there a way to make it work or do I have to use Regex to first figure out which pattern I need and then use it for parsing?
appendPatterndoes, because it doesn't add alternatives, it extends the pattern of the builder.