【问题标题】:check valid date in java在java中检查有效日期
【发布时间】:2022-02-15 00:42:25
【问题描述】:

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

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

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

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.

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

【问题讨论】:

    标签: java date


    【解决方案1】:

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

    • 使用uuuu 代替yyyy。尝试后者很容易,但y 表示“ERA 中的年份”。不知道是BC还是AD。 u 表示“年份”,包括 ERA 信息。
    • default resolver styleSMART。使用 .withResolverStyle(ResolverStyle.STRICT) 返回格式化程序的 strict 副本。

    【讨论】:

    • 不仅“显然”,documentation 明确指出:“它使用 SMART 解析器样式。”
    • 是的,我看到了,只是我自己还没有意识到这一点。
    • 总结一下:uuuu在这里检查ERA,因此有助于检查年份是否为闰年。和.withResolverStyle(ResolverStyle.STRICT) 检查Month 1, 3, 5, 7, 8, 10, 12, max 31 days. Month 4, 6, 9, 11, max 30 days.。而SMART 只需检查 1 和 12 内的飞蛾和 1 和 31 内的天。我说得对吗?
    【解决方案2】:

    你需要开启 DateTimeFormatter 的严格模式:

    DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy")
                                .withResolverStyle(ResolverStyle.STRICT);
    

    LocaleDate.parse("30/02/2022, formater); 然后会抛出异常。

    【讨论】:

    • 下面我说了,你需要使用uuuu而不是yyyy,否则你会得到其他异常。
    • 严格来说是对的,想法是对的,但还不够。它抛出java.time.format.DateTimeParseException: Text '30/02/2022' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=30, MonthOfYear=2, YearOfEra=2022},ISO of type java.time.format.Parsed。但是如果我改用28/02/2022,它会抛出一个非常相似的异常,所以我们不能用它来区分有效和无效的日期。
    • @OleV.V.这就是uuuu 修复的问题。这使用字段Year 而不是YearOfEra,因此2022 是公元2022 年而不是2022 年(不知道是公元还是公元前)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 2020-01-24
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多