parseStrict() 与 parseLinient() DateTimeFormatterBuilder java

问题描述 投票:0回答:1
String validInput = "2023-12-31";

String lenientInput = "2023-12-31  "; // Extra space


DateTimeFormatter strictFormatter = new DateTimeFormatterBuilder()

   .appendPattern("yyyy-MM-dd")

   .parseStrict()

   .toFormatter();


DateTimeFormatter lenientFormatter = new DateTimeFormatterBuilder()

.appendPattern("yyyy-MM-dd")

.parseLenient()

.toFormatter();

LocalDate strictDate = LocalDate.parse(**validInput, strictFormatter**);

System.out.println("Strict: " + strictDate);   //OK WORKS

LocalDate lenientDate = LocalDate.parse(**lenientInput, lenientFormatter**);

System.out.println("Lenient: " + lenientDate); // but Failed 

我无法理解 parseStrict() 与 parseLinient() 之间的确切区别

我尝试了很多模式,大多数模式在我使用的模式中都工作相似。

java
1个回答
0
投票

这不是一个严格的格式化程序。您需要使用

.withResolverStyle(ResolverStyle.STRICT)
来获得严格的格式化程序。一旦有了一个,宽松和严格格式化程序之间的区别就在于输入的日期无效。例如,闰年的 2 月 30 日。这不是一个有效的日期。宽松的解析器将对其进行评估并返回 2 月 29 日。严格的解析器将抛出异常。在代码中,可能看起来像,

public static void main(String[] args) throws Exception {
    DateTimeFormatter strictFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") //
            .withResolverStyle(ResolverStyle.STRICT);

    DateTimeFormatter lenientFormatter = new DateTimeFormatterBuilder() //
            .appendPattern("yyyy-MM-dd") //
            .parseLenient() //
            .toFormatter();

    String invalidDate = "2024-02-30";
    System.out.println(LocalDate.parse(invalidDate, lenientFormatter));
    System.out.println(LocalDate.parse(invalidDate, strictFormatter));
}

输出

2024-02-29
Exception in thread "main" java.time.format.DateTimeParseException: Text '2024-02-30' could not be parsed: Unable to obtain LocalDate ...
© www.soinside.com 2019 - 2024. All rights reserved.