方法一:經過Calendar類得日期比較,在這須要考慮閏年和平年,也要考慮跨年份spa
/** * date2比date1多的天數 * @param date1 * @param date2 * @return */ public static int differentDays(Date date1,Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); int day1= cal1.get(Calendar.DAY_OF_YEAR); int day2 = cal2.get(Calendar.DAY_OF_YEAR); int year1 = cal1.get(Calendar.YEAR); int year2 = cal2.get(Calendar.YEAR); if(year1 != year2) //不同一年 { int timeDistance = 0 ; for(int i = year1 ; i < year2 ; i ++) { if(i%4==0 && i%100!=0 || i%400==0) //閏年 { timeDistance += 366; } else //不是閏年 { timeDistance += 365; } } return timeDistance + (day2-day1) ; } else //同一年 { System.out.println("判斷day2 - day1 : " + (day2-day1)); return day2-day1; } }
方法二:轉化爲毫秒數,再除以一天得毫秒數code
/** * 經過時間秒毫秒數判斷兩個時間的間隔 * @param date1 * @param date2 * @return */ public static int differentDaysByMillisecond(Date date1,Date date2) { int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24)); return days; }