1360. Number of Days Between Two Dates
Description
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
.
Solutions
Solution 1: Mathematics
First, we define a function isLeapYear(year)
to determine whether the given year year
is a leap year. If it is a leap year, return true
, otherwise return false
.
Next, we define another function daysInMonth(year, month)
to calculate the total number of days in the given year year
and month month
. We can use an array days
to store the number of days in each month, where days[1]
represents the number of days in February. If it is a leap year, it is $29$ days, otherwise it is $28$ days.
Then, we define another function calcDays(date)
to calculate the number of days from the given date date
to 1971-01-01
. We can use date.split("-")
to split the date date
into year year
, month month
, and day day
by -
. Then we can use a loop to calculate the total number of days from 1971
to year
, then calculate the total number of days from January to month
, and finally add day
days.
Finally, we only need to return the absolute value of calcDays(date1) - calcDays(date2)
.
The time complexity is $O(y + m)$, where $y$ represents the number of years from the given date to 1971-01-01
, and $m$ represents the number of months of the given date. The space complexity is $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 29 30 31 32 33 |
|
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 29 30 |
|
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 29 30 31 |
|