DateTimeFormatter自动更正无效(语法上可能)的日历日期

编程入门 行业动态 更新时间:2024-10-11 15:16:40
本文介绍了DateTimeFormatter自动更正无效(语法上可能)的日历日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Java DateTimeFormatter 当您尝试超出可能范围的日期时抛出异常,例如:

Java DateTimeFormatter throws an exception for when you try a date that goes outside of a possible range, for example:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy"); String dateString = "12/32/2015"; LocalDate ld = LocalDate.parse(dateString, dtf);

将抛出:

Exception in thread "main" java.time.format.DateTimeParseException: Text '12/32/2015' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32

但是,当我输入一个无效的日历日期时,他们的标准仍然是语法上可行的,它会自动更正为有效日期,例如:

But when I enter an invalid calendar date that is still syntactically possible by their standards, it autocorrects it to be a valid date, for example:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy"); String dateString = "2/31/2015"; LocalDate ld = LocalDate.parse(dateString, dtf);

它成功解析但自动更正为 2015-02-28 。我不想这个行为,我希望它在日期不是有效的日历日期时仍然抛出异常。有没有一个可以设置的内置选项,或者我真的需要尝试手动筛选出这些实例?

it successfully parses but autocorrects to 2015-02-28. I don't want this behavior, I want it to still throw an exception when the date is not a valid calendar date. Is there a built-in option I can set for that to happen, or do I really have to try to manually sift out these instances?

推荐答案

您可以使用 STRICT 解析器样式:

You can use a STRICT resolver style:

import static java.time.format.ResolverStyle.STRICT; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uuuu").withResolverStyle(STRICT);

默认情况下, ofPattern 使用 a SMART 解析器样式将使用合理的默认值。

By default, ofPattern uses a SMART resolver style which will use reasonable defaults.

请注意,我已经使用 uuuu 的 yyyy ,即 YEAR ,而不是 YEAR_OF_ERA 。假设你是一个公历的系统,这两个在当前时代(1年级以上)相当多年。差异在上面的链接中有更多的细节。

Note that I have used uuuu instead of yyyy, i.e. YEAR instead of YEAR_OF_ERA. Assuming you are in a Gregorian calendar system, the two are equivalent for years in the current era (year 1 or greater). The difference is explained in more details in the links above.

更多推荐

DateTimeFormatter自动更正无效(语法上可能)的日历日期

本文发布于:2023-11-22 06:10:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616266.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   日历   日期   DateTimeFormatter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!