功能: check日期是否合法 (主要實現某年某月日期是否超過當月最大日期的合法性判斷)
測試數據: 20070229 false
20070228 false
20040229 true
/**
* 日期合法check
*
* @param date 需要check的日期
* @return 日期是否合法
*/
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;
}