gpt4 book ai didi

java - LocalDate.parse 是否会默默地更正天数?

转载 作者:行者123 更新时间:2023-12-04 16:39:43 25 4
gpt4 key购买 nike

String s = "2020 Jun 31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MMM dd");
LocalDate date = LocalDate.parse(s, formatter);
System.out.println(date);
输出:
2020-06-30
为什么 31 变成 30 没有任何警告或异常?

最佳答案

DateTimeFormatter 有一个 ResolverStyle这会影响解析器对无效日期和时间值的严格程度或宽松程度。要在这种情况下获得异常,您需要将解析器样式设置为 STRICT。
您还需要使用 u (年) 而不是 y (年代)在格式字符串中。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu MMM dd")
.withResolverStyle(ResolverStyle.STRICT);
默认解析器类型为 SMART :

Using smart resolution will perform the sensible default for each field, which may be the same as strict, the same as lenient, or a third behavior. Individual fields will interpret this differently.

For example, resolving year-month and day-of-month in the ISO calendar system using smart mode will ensure that the day-of-month is from 1 to 31, converting any value beyond the last valid day-of-month to be the last valid day-of-month.

关于java - LocalDate.parse 是否会默默地更正天数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63315211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com