请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
示例 2:
输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15
提示:
给定的日期是 1971 年到 2100 年之间的有效日期。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-days-between-two-dates
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
转成天,就是 365*年+闰年数+当年的天数
int isleap(int y){
return y%4==0 && y%100!=0 || y%400==0;
}
int tab[]={-1,31,28,31,30,31,30,31,31,30,31,30,31};
int getdate1(char *date){
int y,m,d,r=0;
sscanf(date, "%d-%d-%d", &y,&m,&d);
for(int i=1970; i
class Solution {
public:
int day_diff(int year_start, int month_start, int day_start
, int year_end, int month_end, int day_end)
{
int y2, m2, d2;
int y1, m1, d1;
m1 = (month_start + 9) % 12;
y1 = year_start - m1/10;
d1 = 365*y1 + y1/4 - y1/100 + y1/400 + (m1*306 + 5)/10 + (day_start - 1);
m2 = (month_end + 9) % 12;
y2 = year_end - m2/10;
d2 = 365*y2 + y2/4 - y2/100 + y2/400 + (m2*306 + 5)/10 + (day_end - 1);
return (d2 - d1);
}
int daysBetweenDates(string date1, string date2) {
int y1,y2,m1,m2,d1,d2;
y1=stoi(date1.substr(0,4));
y2=stoi(date2.substr(0,4));
m1=stoi(date1.substr(5,2));
m2=stoi(date2.substr(5,2));
d1=stoi(date1.substr(8,2));
d2=stoi(date2.substr(8,2));
return abs(day_diff(y1,m1,d1,y2,m2,d2));
}
};