思路:
(1) 通过Calendar类来计算
Calendar c1 = Calendar.getInstance();
Calendar c2= Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int day1 = c1.get(Calendar.DAY_OF_YEAR);
int day2 = c2.get(Calendar.DAY_OF_YEAR);
int year1 = c1.get(Calendar.YEAR);
int year2 = c2.get(Calendar.YEAR);
if(year1 != year2){
int timeStance =0;
for(int i=year1; i<year2; i++){
// 判断每一年是不是闰年
if(i%4==0&& i%100!=0 || i%400==0){
timeStance +=366;
}else{
timeStance +=365;
}
}
return timeStance+(day2-day1);
}else{
return day2-day1;
}
}
(2)通过timeStamp 计算
long timeDiff = date2.getTime() - date1.getTime();
int days = (int)(timeDiff/(1000*3600*24))
在计算days的时候 要注意是将最终计算结果转换成为int类型,而不是将timeDIff转换成int类型,因为timeDiff是long转换成int时会丢失精度 导致最大值不会超过int的最大值
计算int的最大值 1l<<32 将1向左移动32位,然后减去1即可