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

DateTimeFormatter auto-corrects invalid (syntactically possible) calendar date(DateTimeFormatter 自动更正无效(语法上可能)的日历日期)
本文介绍了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 使用 一种 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 自动更正无效(语法上可能)的日历日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)