记录一下常见的日期问题模板
判断闰年
闰年规则
(1)能被4整除且不能被100整除
(2)能被400整除
static boolean check(int year) {
if((year%4==0&&year%100!=0)||(year%400==0))
return true;
return false;
}
判断星期几
基姆拉尔森计算公式,通过年月日三个参数直接计算出星期
static int check(int y,int m,int d) {
int w= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1)%7;
return w;
}
判断日期合法性
这里常规方法的话判断闰年判断月日是真麻烦,还是用java的日期类来判断方便的多
static boolean check(int y,int m,int d) {
String s=y+"-"+m+"-"+d;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//定义日期格式年-月-日
sdf.setLenient(false);//严格判断日期合法
try {
sdf.parse(s);//不合法抛异常
} catch (ParseException e) {
return false;
}
return true;
}
可以的