public static int getIntervalDays(Date oldDate,Date newDate){
if(oldDate.after(newDate)){
throw new IllegalArgumentException("时间先后顺序不对!");
}
//将转换的两个时间对象转换成Calendard对象
Calendar can1 = Calendar.getInstance();
can1.setTime(oldDate);
Calendar can2 = Calendar.getInstance();
can2.setTime(newDate);
//拿出两个年份
int year1 = can1.get(Calendar.YEAR);
int year2 = can2.get(Calendar.YEAR);
//天数
int days = 0;
Calendar can = null;
//减去小的时间在这一年已经过了的天数
//加上大的时间已过的天数
days -= can1.get(Calendar.DAY_OF_YEAR);
days += can2.get(Calendar.DAY_OF_YEAR);
can = can1;
for (int i = 0; i < Math.abs(year2-year1); i++) {
//获取小的时间当前年的总天数
days += can.getActualMaximum(Calendar.DAY_OF_YEAR);
//再计算下一年。
can.add(Calendar.YEAR, 1);
}
return days;
}
java 获取两个时间相差天数
最新推荐文章于 2024-07-15 03:42:30 发布