需要验证日期方面的帮助
我有下面的代码,它运行得很好,除非您输入类似 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 格式”?
I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message "The Document Date is not a valid date". I would expect that it would say "The Document Date needs to be in the format MM/DD/YYYY".
Why does the line newDate = dateFormat.parse(date);
not catch that?
// 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";
}
}
EDIT: I'm trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters "2/2/2011", it will display the message: "The Document Date needs to be in the format MM/DD/YYYY"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如已经提到的,
SimpleDateFormat
能够解析“2/2/2011”,就好像它是“02/02/2011”一样。所以不会抛出ParseException。另一方面,
dateFormat.format(newDate)
将返回“02/02/2011”并与“2/2/2011”进行比较。两个字符串不相等,因此返回第二条错误消息。setLenient(false)
在这种情况下不起作用:(来源:java docs)
您可以使用正则表达式手动检查字符串格式:
As already mentioned, the
SimpleDateFormat
is able to parse "2/2/2011" as if it is "02/02/2011". so noParseException
is thrown.On the other hand,
dateFormat.format(newDate)
will return "02/02/2011" and is compared against "2/2/2011". The two strings aren't equal, so the second error message is returned.setLenient(false)
will not work in this case:(source: java docs)
you can use a regular expression to manually check the string format:
日期是正确的,但它的格式将是 02/02/2002
The date is correct, but it will be formatted as 02/02/2002