Calendar类计算两个日期的差,需要转化成毫秒计算,然后再转化成天
例:
import java.util.Calendar;
public class Test{
public static void main(String[] args){
Calendar a = Calendar.getInstance(),
b = Calendar.getInstance();
a.set(2015, Calendar.MARCH, 31);
b.set(2015, Calendar.APRIL, 1);
long diffDays = (b.getTimeInMillis() - a.getTimeInMillis()) / (1000 * 60 * 60 * 24);
System.out.println(diffDays);
}
}
只要利用Calendar的add()方法让前者日期的天数无限循环递增 一直递增到后者日期循环结束 然后把循环次数记录下来 循环次数就是两者日期相隔的天数(因为循环到日期相同的时候循环次数任然递增了1天 所以相隔天数必须减1)
public class CalendarDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=0;
Calendar c = Calendar.getInstance();
//起始位2017.4.3日(月份角标是从0开始的)
c.set(2017,3,3);
while(!(c.get(Calendar.YEAR)==2020&&c.get(Calendar.MONTH)==4&&c.get(Calendar.DAY_OF_MONTH)==1)) {
//终止时间是2020.5.1日,每次天数递增1
c.add(Calendar.DAY_OF_MONTH,1);
count++;
}
sop(count);
}
public static void sop(Object obj) {
System.out.println(obj);
}
}
public static long daysBetween(Date d1, Date d2) {
if ( (d1 == null) || (d2 == null)) {
return 0;
}
long ld1 = d1.getTime();
long ld2 = d2.getTime();
long days = (long) ( (ld2 - ld1) / 86400000);
return days;
}