不调库
class Solution {
public:
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 days[2][13]= {{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};
int res = 0;
if(year1 > year2 || (year1 == year2 && month1 > month2) || (year1 == year2 && month1 == month2 && day1 > day2))
{
swap(year1,year2);
swap(month1,month2);
swap(day1,day2);
}
for(int i = year1; i < year2; i++)
{
if((i%4 == 0 && i % 100 != 0 ) || (i % 400 == 0))
{
res += 366;
}
else
{
res += 365;
}
}
bool flag = (year2%4 == 0 && year2 % 100 != 0 ) || (year2 % 400 == 0);
for(int i = 1; i < month2; i++)
{
res += days[flag][i];
}
res += day2;
flag = (year1%4 == 0 && year1 % 100 != 0 ) || (year1 % 400 == 0);
for(int i = 1; i < month1; i++)
{
res -= days[flag][i];
}
res -= day1;
return res;
}
};
调库:
class Solution {
public:
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));
struct tm a = {0};
struct tm b = {0};
a.tm_year = year1 - 1900;
a.tm_mon = month1 - 1;
a.tm_mday = day1;
b.tm_year = year2 - 1900;
b.tm_mon = month2 - 1;
b.tm_mday = day2;
double second = difftime(mktime(&b),mktime(&a));
return abs(second)/(24*60*60);
}
};