网上很多用这种判断的:对string转date抛异常
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(sDate);
return sDate.equals(formatter.format(date));
} catch (Exception e) {
return false;
}
但是会有一种情况,也成功:
比如sDate = "2021-09-09 19:54:20!!"
所以这种方式不是完全正确的!!!!!!!!!!!!! ,当然事先加个长度校验也行。
可以用如下方式,或正则
static int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
//只处理 yyyy-MM-dd HH:mm:ss
public static boolean isValidDate(String date) {
try {
if(date == null) {
return false;
}
if(date.length() != 19){
return false;
}
int year = Integer.parseInt(date.substring(0, 4));
if (year <= 0)
return false;
int month = Integer.parseInt(date.substring(5, 7));
if (month <= 0 || month > 12)
return false;
int day = Integer.parseInt(date.substring(8, 10));
if (day <= 0 || day > DAYS[month])
return false;
if (month == 2 && day == 29 && !isGregorianLeapYear(year)) {
return false;
}
int hour = Integer.parseInt(date.substring(11, 13));
if (hour < 0 || hour > 23)
return false;
int minute = Integer.parseInt(date.substring(14, 16));
if (minute < 0 || minute > 59)
return false;
int second = Integer.parseInt(date.substring(17, 19));
if (second < 0 || second > 59)
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}