JAVA 判断一个字符串是否是合法的日期格式?


采用SimpleDateFormat类的parse方法进行判断,如果转换不成功,就会出现异常。另外,还需要判断字符串的长度,若不判断,第二个字符串就会验证通过,实际上也不是合法的。话不多说,且看代码:

public static void main(String[] args) {
        System.out.println(isValidDate("2020-12-12 14:30:20", null));//true
        System.out.println(isValidDate("19-12-12 14:30:20", null));//false
        System.out.println(isValidDate("2020/12/12 14:30:20", null));//false
        System.out.println(isValidDate("2020-12-12 14:30", null));//false
    }


    public static boolean isValidDate(String str, String format) {
        if (format == null) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        boolean convertSuccess = true;
        // 指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            sdf.setLenient(false);
            sdf.parse(str);
            if (str.length() != format.length()) {
                convertSuccess = false;
            }
        } catch (ParseException e) {
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM