1--Java
分析:调用java中Calendar类
int days(Date date1,Date date2){ Calendar cal = new Calendar.getInstance(); cal.setTime(date1); int time1 = cal.get(Calendar.DAY_OF_YEAR); cal.setTime(date2); int time2 = cal.get(Calendar.DAY_OF_YEAR); //long days = Math.abs(time1-time2)/(24*3600*1000); return Math.abs(day1-day2); }
2--java
int days(Date date1,Date date2){ long time1 = Math.abs(date1.getTime()-date2.getTime()); return (int)time1/(24*3600*1000); }
分析:首先要知道关于闰年的概念,每四年一润,四百年润,且不能被100整除。因为,闰年二月有29天,全年共计366天。
伪代码:首先将日期字符串的年,月,日分开,类型为yyyy-mm-dd,得到两个日期,year1,month1,day1,year2,month2,day2
如果年份,月份相同:
return day1-day2;(大减小)
如果年份相同,月份不同:
计算date1,该年过了多少天D1;date2,该年过了多少天D2
return D1-D2;
如果,年份不同:
D1=date1 是该年的第多少天
D2=date2距离该年该年结束还有多少天
D3=两个年份之间相差的整年数是多少天
return D1+D2+D
#include <iostream> using namespace std; public bool stringToDate(string date,int &year,int &month,int &day){ year = atoi(date.substr(0,4).c_str()); month=atio(date.substr(5,2).c_str()); day=atio(date.substr(8,2).c_str()); Day[12]={31,29,31,30,31,30,31,31,30,31,30,31}; if(isLear(year)) Day[1]=29; return year>0&&month>0&&month<=12&&day<=Day[month-1]; } public bool isLeap(int year){ return ((year%4==0)||(year%400==0))&&(year&100!=0); } public int daysInYear(int year,int month ,int day){ int days = day; int Day[12]={31,28,31,30,31,30,31,31,30,31,30,31}; if(isLeap(year)) Day[1]=29; for(int i=0;i<month-1;i++){ days+=Day[i]; } return days; } public between_days(string date1,string date2){ if(stringToDate(date1,int &year1,int &month1,int &day1)&&stringToDate(string date2,int &year2,int &month2,int &day2)){ if(year1==year2&&month1==month2){ return day1>day2?day1-day2:day2-day1; } else if(year1==year2){ int d1 = daysInYear(year1,month1,day1); int d2 = daysInYear(year2,month2,day2); return d1>d2?d1-d2:d2-d1; } else{ if(year1<year2){ swap(year1,year2); swap(month1,month2); swap(day1,day2); } int D1=0; for(int j=year2+1;j<year1;j++){ if(isLeap(j)) D1+=366; else D1+=365; } int D2=daysInYear(year1,month1,day1); if(isLeap(year2)) D2=D2+366-daysInYear(year2,month2,day2); else D2=D2+365-daysInYear(year2,month2,day2); return D1+D2; } } }