我有下面的代码,它工作得很好,除非您输入类似 2/2/2011 的内容,您会收到错误消息“文档日期不是有效日期”。我希望它会说“文档日期需要采用 MM/DD/YYYY 格式”。
为什么线路newDate = dateFormat.parse(date);
没有捕捉到?
// checks to see if the document date entered is valid
private String isValidDate(String date) {
// set the date format as mm/dd/yyyy
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date newDate = null;
// make sure the date is in the correct format..
if(!date.equals("mm/dd/yyyy")) {
try {
newDate = dateFormat.parse(date);
} catch(ParseException e) {
return "The Document Date needs to be in the format MM/DD/YYYY\n";
}
// make sure the date is a valid date..
if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
return "The Document Date is not a valid date\n";
}
return "true";
} else {
return "- Document Date\n";
}
}
编辑:我正在尝试严格遵守格式 MM/DD/YYYY。如何更改代码,以便如果用户输入“2/2/2011”,它将显示消息:“文档日期需要采用 MM/DD/YYYY 格式”?