Java SimpleDateFormat 接受无效日期。使用格式 'MM/dd/yyyy' 解析 '01/01/2021anything'

Java SimpleDateFormat accepts invalid date. with format 'MM/dd/yyyy' parses '01/01/2021anything'

我正在尝试将字符串日期值解析为日期对象。 如果提供的日期格式不正确,则必须抛出错误。 尝试使用 SimpleDateFormat 实现此目的,但未按预期工作。

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(false);
Date d = sdf.parse("01/01/2021anything");
System.out.println(d);

对于上面的代码,在我预期的地方 ParseException 得到了输出 Fri Jan 01 00:00:00 GMT 2021。有人可以解释为什么会发生这种情况以及我如何使用 SimpleDateFormat 验证上述日期。感谢您的努力。

发生这种情况是因为它是以这种方式实现的。

SimpleDateFormat 将检查格式,并开始解析格式中存在的每个标记,但不一定解析整个字符串,根据 the docs:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

无论如何你都不应该使用 SimpleDateFormatDate,因为它们比这个 more problems

改用 java.time 包中的 类。在您的情况下,您可能应该使用 LocalDate。使用 java.time 将您的代码简单转换为代码如下:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate d = LocalDate.parse("01/01/2021anything", formatter);
System.out.println(d);

上面提到的代码会抛出一个DateTimeParseException,因为它不喜欢任何东西