1.使用SimpleDateFormat类
public static boolean CheckDate(String str){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
simpleDateFormat.setLenient(false);
try {
Date date=simpleDateFormat.parse(str);
return true;
}catch (ParseException e){
return false;
}
}
该类的parse方法执行成功则证明该日期合法
2.手打手判断
static int months[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
public static boolean check_valid(int date){
int year=date/10000;
int month=date%10000/100;
int day=date%100;//分离年月日
if(day==0||month<=0||month>12)return false;//显然的不合法情况
if(month!=2&&day>months[month])return false;//月份不是2,day不合法就不合法
if(month==2){//月份是2
if((year%4==0&&year%100!=0)||(year%400==0))if(day>29)return false;//是闰月, day必须<=29
else if(day>28)return false;//是平月,day必须<=28
}
return true;
}
闰年的条件:1.可以被4整除但不能被100整除
2.可以被400整除
核心判断方法:
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)