java - 在验证日期方面需要帮助

标签 java date simpledateformat

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

最佳答案

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

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

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

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

(来源:java docs)

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

if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
    // parse the date
} else {
    // error: wrong format
}

关于java - 在验证日期方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6207280/

相关文章:

java - 如果方法读取下一行为空则停止循环

java - 将 XMLGregorianCalendar 转换为日期,即 "MM/DD/YYYY hh:mm:ss AM"

java - 字符串转换为时间(仅 hh :mm)

java - 为什么Java时间戳解析在毫秒部分前缀0?

java - 使用 Java 8 日期时间 API 时如何将 AM/PM 符号更改为我自己的字母表

G1 的 java GC 堆参数

java - Firebase 不断更改值并添加新子项

java - spring jdbc连接远程mysql失败,而localhost正常

php - 突出显示具有相同日期和几乎相同时间的行

c++ - 将 time_duration 转换为 DATE