【问题标题】:Date Format validation not working for yyyy-MM-dd日期格式验证不适用于 yyyy-MM-dd
【发布时间】:2016-01-15 12:12:32
【问题描述】:

我想以 yyyy-MM-dd 格式验证日期。 如果我给出两位数的年份(即 YY 而不是 YYYY),它不会引发任何异常,并且 00 会在解析日期时附加到日期时间格式。

我添加了setLenient(false);,但仍然无法正确验证。

谁能帮我解决这个问题?

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
try {
   Date date = (Date)formatter.parse("15-05-30"); //In this line year is getting appened with 00 and becomes 0015
   reciptDate = dateFormat.format(date);
} catch (ParseException pe) {
   return false;
}

【问题讨论】:

  • 为什么不简单地解析"2015-05-30"?你有什么理由想要另一个SimpleDateFormat 而不是你实际需要的吗?
  • 如果格式与 yyyy-MM-dd 不匹配,我们想抛出一些异常
  • stackoverflow.com/questions/18534343/… 请参阅此链接。如果年份小于假设 2000,您可能应该定义一个额外的检查。除此之外,15 是一年的有效数字。
  • 例如:if (date.before(new Date(0L))) return false;

标签: java date simpledateformat


【解决方案1】:

API docs for SimpleDateFormat 指定年份

对于解析,如果模式字母的数量超过 2 个,则按字面解释年份,而不考虑位数。因此,使用“MM/dd/yyyy”、“01/11/12”模式会解析到公元 12 年 1 月 11 日

因此,您不能按原样使用SimpleDateFormat 来执行您想要的验证(请注意,1、2 或 3 位数年份是有效年份,> 4 位数年份也是如此,但我认为这是超出了问题的范围)。

使用正则表达式验证您恰好有 4 位数的年份应该是微不足道的。

例如:

Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");

System.out.println("15-05-30: " + pattern.matcher("15-05-30").matches());
System.out.println("2015-05-30: " + pattern.matcher("2015-05-30").matches());
System.out.println("0015-05-30: " + pattern.matcher("0015-05-30").matches());

输出:

15-05-30: false
2015-05-30: true
0015-05-30: true

【讨论】:

    【解决方案2】:

    如果您使用的是 Java-8,您可以指定 年份组件的最小宽度。

    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(ChronoField.YEAR, 4, 4, SignStyle.NEVER)
        .appendPattern("-MM-dd")
        .toFormatter();
    LocalDate date = LocalDate.parse("15-05-30", fmt);
    

    错误信息是:

    线程“主”java.time.format.DateTimeParseException 中的异常:

    无法在索引 0 处解析文本“15-05-30”

    在 java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)

    在 java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

    在 java.time.LocalDate.parse(LocalDate.java:400)

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 2022-11-29
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多