3

我有下面的代码,它工作得很好,除非您输入类似 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 格式”?

4

2 回答 2

4

如前所述,SimpleDateFormat能够将“2/2/2011”解析为“02/02/2011”。所以没有ParseException抛出。

另一方面,dateFormat.format(newDate)将返回“02/02/2011”并与“2/2/2011”进行比较。两个字符串不相等,因此返回第二条错误消息。

setLenient(false)在这种情况下不起作用:

月份:如果模式字母的个数为3个或更多,则将月份解释为文本;否则,它被解释为一个数字

数字:对于格式化,模式字母的数量是最小位数,较短的数字在此数量上补零。对于parsing,除非需要分隔两个相邻字段,否则会忽略模式字母的数量。

(来源:java 文档

您可以使用正则表达式手动检查字符串格式:

if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
    // parse the date
} else {
    // error: wrong format
}
于 2011-06-01T21:04:20.230 回答
0

日期正确,但格式为 02/02/2002

于 2011-06-01T20:37:46.550 回答