检查java中的有效日期

hoà*_*yễn 6 java date

我尝试使用如下String格式检查输入是否为有效日期:dd/MM/yyyy

String input = Scanner.nextLine();
DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try{
    LocaleDate.parse(input, formater);
}
catch(Exception e)
Run Code Online (Sandbox Code Playgroud)

但它无法检查以下一些规则:

Leap year, February 29 days.

Common year, February 28 days.

Month 1, 3, 5, 7, 8, 10, 12, max 31 days.

Month 4, 6, 9, 11, max 30 days.
Run Code Online (Sandbox Code Playgroud)

当我使用时input = "30/02/2022",它是合法的。我用netbeans 8.2jdk 1.8。他们支持一些检查这些规则的方法吗?

Rob*_*oor 11

您需要在格式化程序中更改两件事:

  • 使用uuuu而不是yyyy. 尝试后者很容易,但y意思是“ERA 内的一年”。它不知道是公元前还是公元。u指“年份”,包括 ERA 信息。
  • 默认解析器样式是SMART. 用于.withResolverStyle(ResolverStyle.STRICT)返回格式化程序的严格副本。

  • 不仅是“显然”,[文档](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ofPattern(java .lang.String)) 明确指出:*“它使用 [SMART](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/ResolverStyle .html#SMART) 解析器样式。"* (4认同)