package test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Time { public static int differentDays(Date date1,Date date2){ Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(date1); 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 timeDistance1 = 0 ; int timeDistance2 = 0 ; for(int i=year2;i<year1;i++){ if(i%4==0 && i%100!=0 || i%400==0){ //闰年 timeDistance1 += 366; } else{ //不是闰年 timeDistance1 += 365; } } if(year2%4==0 && year2%100!=0 || year2%400==0){ //闰年 timeDistance2 +=1; } return (day1+timeDistance1-day2-timeDistance2) ; }else{ //同年 return day1-day2; } } public static void main(String[] args) throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM Date date1 = simpleDateFormat.parse("2020-01-01"); Date date2 = simpleDateFormat.parse("2019-12-25"); System.out.println(differentDays(date1,date2)); } }
原文:https://www.cnblogs.com/lifan12589/p/12220998.html