# 1360. Number of Days Between Two Dates¶

• Time: $O(1)$
• Space: $O(1)$
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public: int daysBetweenDates(string date1, string date2) { return abs(daysFrom1971(date1) - daysFrom1971(date2)); } private: const vector days{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int daysFrom1971(const string& date) { const int year = stoi(date1.substr(0, 4)); const int month = stoi(date1.substr(5, 2)); const int day = stoi(date1.substr(8, 2)); int res = 0; for (int i = 1971; i < year; ++i) res += isLeapYear(i) ? 366 : 365; for (int i = 0; i < month; ++i) res += days[i]; if (month > 2 && isLeapYear(year)) ++res; res += day; return res; } bool isLeapYear(int year) { return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; }; };
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public int daysBetweenDates(String date1, String date2) { return Math.abs(daysFrom1971(date1) - daysFrom1971(date2)); } private static final int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; private int daysFrom1971(final String date) { final int year = Integer.valueOf(date.substring(0, 4)); final int month = Integer.valueOf(date.substring(5, 7)); final int day = Integer.valueOf(date.substring(8)); int res = 0; for (int i = 1971; i < year; ++i) res += isLeapYear(i) ? 366 : 365; for (int i = 0; i < month; ++i) res += days[i]; if (month > 2 && isLeapYear(year)) ++res; return res + day; } private boolean isLeapYear(int year) { return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; }; }
 1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def isLeapYear(year: int) -> bool: return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def daysFrom1971(date: str) -> int: year, month, day = map(int, date.split('-')) return 365 * (year - 1971) + sum(map(isLeapYear, range(1971, year))) + \ sum(days[:month]) + day + (month > 2 and isLeapYear(year)) return abs(daysFrom1971(date1) - daysFrom1971(date2))