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
Constraints:
- The given dates are valid dates between the years
1971
and2100
.
Solution: Convert to days since epoch
Time complexity: O(1)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: int daysBetweenDates(string date1, string date2) { array<int, 12> m{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; auto isLeap = [](int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); }; auto daysFromEpoch = [&](const string& date) { int year = stoi(date.substr(0, 4)); int month = stoi(date.substr(5, 2)); int days = stoi(date.substr(8, 2)); for (int i = 1970; i < year; ++i) days += 365 + isLeap(i); for (int i = 1; i < month; ++i) days += m[i - 1]; days += month > 2 && isLeap(year); return days; }; return abs(daysFromEpoch(date1) - daysFromEpoch(date2)); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment