解题思路:
(1)为方便起见,我们从某一个固定的时间计算总的天数,比如1970年
class Solution {
public :
int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
public:
bool isleap(int year) {
if((year%4==0 && year%100!=0) || year%400==0) return true;
else return false;
}
int calculate_days(int year,int month,int day) {
int sum_days = 0;
for(int i=1970;i<year;i++) {
if(isleap(i)) sum_days+=366;
else sum_days+=365;
}
for(int i=1;i<month;i++) {
if(i==2 && isleap(year)) sum_days+=29;
else sum_days+=months[i-1];
}
sum_days+=day;
return sum_days;
}
int daysBetweenDates(string date1, string date2) {
int year1 = stoi(date1.substr(0,4));
int month1 = stoi(date1.substr(5,2));
int day1 = stoi(date1.substr(8,2));
int year2 = stoi(date2.substr(0,4));
int month2 = stoi(date2.substr(5,2));
int day2 = stoi(date2.substr(8,2));
int a = calculate_days(year1,month1,day1);
int b = calculate_days(year2,month2,day2);
return abs(a-b);
}
};