【发布时间】:2011-06-01 20:32:08
【问题描述】:
我有下面的代码,它工作得很好,除非您输入类似 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 格式”?
【问题讨论】:
-
很多这段代码没有做任何有用的事情。可以提供一个更简单的代码示例,因为我很想删除大部分代码。
-
2是一个有效的年份,所以我不希望它产生错误,我希望它格式化为02/02/0002这与2/2/2甚至 6/1 不一样/2011 将无法通过您的测试。 -
应该是 2011 年 2 月 2 日。我已经更新了。
-
这将被格式化为您指定的
02/02/2011,因此它不会匹配。 -
不,不会的。它给出消息“文档日期不是有效日期”。我希望它给出消息“文档日期需要采用 MM/DD/YYYY 格式”。
标签: java date simpledateformat