1360. Number of Days Between Two Dates

https://leetcode.com/problems/number-of-days-between-two-dates/

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

Example 1:

Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1

Example 2:

Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15

给两个以xxxx-xx-xx为格式的日期(>=1971年),问它们之间相差多少天。计算两个日期分别与1971年1月1日差了多少天。对给定日期计算在它的年是第几天,再从1971数到该年差了多少年,对每年是闰年加366年否则加365天。

代码参考自

class Solution {
public:
    int daysFrom1971(string date) {
        vector<int> days{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        const auto leap = [](int y) {
            return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
        };
        int y = stoi(date.substr(0, 4)), m = stoi(date.substr(5, 2)), d = stoi(date.substr(8, 2));
        if (m > 2 && leap(y)) ++d;
        while (--m > 0) d += days[m - 1];
        while (--y > 1970) d += leap(y) ? 366 : 365;
        return d;
    }
    
    int daysBetweenDates(string date1, string date2) {
        return abs(daysFrom1971(date1) - daysFrom1971(date2)); 
    }
};

Last updated