为什么无效日期会成功解析为真实日期?

Why does an invalid date parses successfully as a real date?

有人可以向我解释如何使用以下方法为显示的输入 return 值 false 吗?这是 returning true,这是我没有预料到的。

isDateValid("19/06/2012 5:00, 21:00","dd/MM/yyyy HH:mm")

我觉得应该returnfalse,但显然Java不这么认为。提供的实际日期字符串在末尾包含这些额外字符:", 21:00".

public static boolean isDateValid(String date, String dateFormat) 
{
        try {
            DateFormat df = new SimpleDateFormat(dateFormat);
            df.setLenient(false);
            Date newDate = df.parse(date);
            System.out.println("Date value after checking for validity: " + newDate);
            return true;
        } catch (ParseException e) {
            return false;
        }
}

parse不一定使用整个String。这在the Javadoc中非常清楚,强调我的:

parse

public Date parse(String source) throws ParseException

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. See the parse(String, ParsePosition) method for more information on date parsing.


您可以使用parse(String text, ParsePosition pos)检测字符串末尾是否有多余的字符。如果 pos 不等于字符串的末尾,则表示末尾还有多余的字符。

这是一个工作程序,包括测试装置,可以按照您想要的方式正确检查。在此程序中,pos.getIndex() 将是 0 如果它根本无法解析,如果末尾有额外字符,则数字太小,如果按您想要的方式工作,则等于

public class DateFormatTest {
  public static void main(String[] args) {
    // should be false
    System.out.println(isDateValid("19/06/2012 5:00, 21:00", "dd/MM/yyyy HH:mm"));
    System.out.println(isDateValid("19/06/201", "dd/MM/yyyy HH:mm"));
    
    System.out.println();
    
    // should be true
    System.out.println(isDateValid("19/06/2012 5:00", "dd/MM/yyyy HH:mm"));
  }

  public static boolean isDateValid(String date, String dateFormat) {
    ParsePosition pos = new ParsePosition(0);
    DateFormat df = new SimpleDateFormat(dateFormat);
    df.setLenient(false);
    df.parse(date, pos);

    return pos.getIndex() == date.length();
  }
}