判断日期是否合法的方法

    public static boolean chkDateFormat(String date) {
        try {
           // 如果输入日期不是8位的,判定为false. 
            if (null == date || "".equals(date) || !date.matches("[0-9]{8}")) {
                return false;
            }
            int year = Integer.parseInt(date.substring(0, 4));
            int month = Integer.parseInt(date.substring(4, 6)) - 1;
            int day = Integer.parseInt(date.substring(6));
            Calendar calendar = GregorianCalendar.getInstance();
            // 当 Calendar 处于 non-lenient 模式时,如果其日历字段中存在任何不一致性,它都会抛出一个异常。
            calendar.setLenient(false);
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DATE, day);
           // 如果日期错误,执行该语句,必定抛出异常.
            calendar.get(Calendar.YEAR);
        } catch (IllegalArgumentException e) {
            return false;
        }
        return true;
    }

这个类是用于判断所输入的日期是否合法

你可能感兴趣的:(Date,String,calendar,null,日历)