日期算法
计算两个日期相差的天数,如果日期年份比1971年小,需要修改1971为更小的值
class Solution {
public:
int daysBetweenDates(string date1, string date2) {
return abs(get(date1) - get(date2));
}
bool leap(int year) {
return (year % 100 != 0 && year % 4 == 0) || (year % 400 == 0);
}
int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int get(string date) {
int year, month, day;
sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day);
int days = 0;
// 1971是年,不能大于要计算的年份
for (int i = 1971; i < year; i++ ) {
days += 365 + leap(i);
}
// 计算月份
for (int i = 1; i < month; i++ ) {
if (i == 2) days += 28 + leap(year);
else days += months[i];
}
// 加上天数
return days + day;
}
};