你可以用DateTimeFormatterBuilder
创建一个有多个图案的DateTimeFormatter
,但LocalDate.parse
似乎不喜欢它.它在单一模式下工作,在多个模式下失败.
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)
}
有没有办法让它工作,或者我必须先用Regex
来确定我需要哪种模式,然后再用它来解析?