/** * 计算两个日期相差天数 */ public static int compareDays(Date date1, Date date2){ Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = Calendar.getInstance(); calendar1.setTime(date1); calendar2.setTime(date2); int day1 = calendar1.get(Calendar.DAY_OF_YEAR); int day2 = calendar2.get(Calendar.DAY_OF_YEAR); int year1 = calendar1.get(Calendar.YEAR); int year2 = calendar2.get(Calendar.YEAR); if(year1 > year2) { int tempyear = year1; int tempday = day1; day1 = day2; day2 = tempday; year1 = year2; year2 = tempyear; } if (year1 == year2) { int days = day2 - day1; System.out.printf("相隔的天数为:%s天", days); return days; } else { int DayCount = 0; for (int i = year1; i < year2; i++) { if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) { DayCount += 366; }else { DayCount += 365; } } System.out.printf("相隔的天数为:%s天", DayCount+(day2-day1)); int days = DayCount+(day2-day1); return days; } } public static void main(String[] args) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s"); Date date1 = null; Date date2 = null; try {// date2 = dateFormat.parse("2019-11-18 12:01:32"); date1 = dateFormat.parse("2019-11-16 23:59:32"); } catch (ParseException e) { e.printStackTrace(); } int i = compareDays(date1, getCurrentDate()); System.out.println(i); }
来源:https://www.cnblogs.com/tubashu/p/11885256.html