【问题标题】:Date validator is not failing when it should日期验证器在它应该失败的时候没有失败
【发布时间】:2022-01-11 10:49:27
【问题描述】:

我的 Spring Boot 应用程序中有一个自定义验证器,该验证器被调用,因为我设置了一个断点并且它停止了。

问题是日期验证器不起作用。

private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMYYYY"); 

@Override
public boolean isValid(String date, ConstraintValidatorContext ctx) {
    // TODO Auto-generated method stub
    if(date == null) {
        return true;
    }
    try {
        DATE_FORMAT.parse(date);
    } catch (Exception e) {
        return false;
    }
    return true;
}

我正在使用无效的日期 785454 对其进行测试,但它没有进入异常。

我的错误在哪里?

【问题讨论】:

  • parse 返回什么值?
  • 1.请改用java.time.*; 2. 你是真的想用YYYY(周年)还是真的是yyyy

标签: java date


【解决方案1】:
  1. 修复模式:SimpleDateFormat("MMyyyy")
  2. 它把月份加起来:
new java.text.SimpleDateFormat("MMyyyy").parse("122000"); = Fri Dec 01 00:00:00 CET 2000
new java.text.SimpleDateFormat("MMyyyy").parse("132000"); = Mon Jan 01 00:00:00 CET 2001
new java.text.SimpleDateFormat("MMyyyy").parse("785454"); = Fri Jun 01 00:00:00 CEST 5460
new java.text.SimpleDateFormat("MMyyyy").parse("015454"); = Sun Jan 01 00:00:00 CET 5454
  1. 唯一的例外是ParseException - if the beginning of the specified string cannot be parsed. (see docs)

以及正确的解决方案(来自评论): setLenientdocumentation 除外

【讨论】:

  • 谢谢!根据您的回复,我看到我需要 DATE_FORMAT.setLenient(false);并将异常更新为 ParseException 之一,它现在正在工作
【解决方案2】:

来自文档Throws: NullPointerException - if text or pos is null.

看起来 parse 方法只有在给定的值为 null 时才会抛出异常。

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多