LocalDate.parse是否默默地纠正了天数? [英] Does LocalDate.parse silently correct day number?

查看:117
本文介绍了LocalDate.parse是否默默地纠正了天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

2020-06-30

为什么31变成30而没有任何警告或异常?

Why does 31 turn into 30 without any warnings or exceptions?

推荐答案

DateTimeFormatter具有

DateTimeFormatter has a ResolverStyle that affects how strict or lenient the parser should be with invalid date and time values. To get an exception in this case you need to set the resolver style to STRICT.

您还需要在格式字符串中使用 u (年份)而不是 y (年代).

You also need to use u (year) instead of y (year-of-era) in the format string.

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.

例如,使用智能模式在ISO日历系统中解析年月和月日,将确保月日从1到31,将超出最后一个有效日期的任何值转换为月份为最后一个有效的月份.

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.

这篇关于LocalDate.parse是否默默地纠正了天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆