我有这个代码来检查日期是否正常,但它并没有惹恼所有情况.例如,当text ="03/13/2009",因为该日期不存在"dd/MM/yyyy"格式,它将日期解析为03/01/2010.当我尝试解析不正确的日期时,有没有办法改变这种行为并获得异常?什么是进行此验证的最佳方法?
public static final String DATE_PATTERN = "dd/MM/yyyy";
public static boolean isDate(String text){
SimpleDateFormat formatter = new SimpleDateFormat(DATE_PATTERN);
ParsePosition position = new ParsePosition(0);
formatter.parse(text, position);
if(position.getIndex() != text.length()){
return false;
}else{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
您需要在解析之前将lenient设置为false,否则解析器将"猜测"并尝试更正无效日期
formatter.setLenient(false);
Run Code Online (Sandbox Code Playgroud)
查看http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#setLenient(boolean)