Number of Days Between Two Dates
EasyPrompt
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: 1Example 2:
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Constraints:
- The given dates are valid dates between the years
1971and2100.
Approaches
2 approaches with complexity analysis and trade-offs.
This brute-force approach involves starting from the earlier of the two dates and incrementing day by day until the later date is reached, while keeping a count of the days passed.
Algorithm
- Parse the input strings
date1anddate2. - Ensure
date1is the earlier date by swapping if necessary. - Initialize a counter
daysto 0. - Loop while
date1is not equal todate2:- Advance
date1to the next calendar day. - Increment the
dayscounter.
- Advance
- Return the final
dayscount.
Walkthrough
First, the two date strings are parsed to extract their year, month, and day components. We then determine which date is earlier to establish a starting point and an ending point. A counter is initialized to zero. We then enter a loop that continues as long as our current date is not the same as the end date. In each iteration of the loop, we advance the current date by one day and increment our counter. The logic for advancing the date must correctly handle month-ends and year-ends, including the special case of leap years for February. For example, when advancing from '2020-02-28', the next day is '2020-02-29' because 2020 is a leap year. When advancing from '2019-12-31', the next day is '2020-01-01'. Once the loop finishes, the counter holds the total number of days between the two dates.
class Solution { public int daysBetweenDates(String date1, String date2) { // Ensure date1 is the earlier date if (date1.compareTo(date2) > 0) { String temp = date1; date1 = date2; date2 = temp; } int[] d1 = parseDate(date1); int[] d2 = parseDate(date2); int days = 0; while (d1[0] != d2[0] || d1[1] != d2[1] || d1[2] != d2[2]) { d1 = getNextDay(d1); days++; } return days; } private int[] parseDate(String date) { String[] parts = date.split("-"); return new int[]{Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2])}; } private int[] getNextDay(int[] date) { int year = date[0]; int month = date[1]; int day = date[2]; day++; if (day > daysInMonth(year, month)) { day = 1; month++; if (month > 12) { month = 1; year++; } } return new int[]{year, month, day}; } private int daysInMonth(int year, int month) { int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (month == 2 && isLeap(year)) { return 29; } return days[month]; } private boolean isLeap(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }}Complexity
Time
O(N), where N is the number of days between the two dates. For dates far apart, this can be very slow. The maximum difference is between 1971 and 2100, which is about 130 years or ~47,500 days.
Space
O(1), as we only use a few variables to store the current date and the counter, regardless of the input.
Trade-offs
Pros
Conceptually simple and easy to follow.
Does not require complex mathematical formulas.
Cons
Inefficient for dates that are far apart.
The implementation of date advancement logic (handling month/year rollovers and leap years) can be tricky and prone to errors.
Solutions
Solution
class Solution {public int daysBetweenDates(String date1, String date2) { return Math.abs(calcDays(date1) - calcDays(date2)); }private boolean isLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); }private int daysInMonth(int year, int month) { int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; days[1] += isLeapYear(year) ? 1 : 0; return days[month - 1]; }private int calcDays(String date) { int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(5, 7)); int day = Integer.parseInt(date.substring(8)); int days = 0; for (int y = 1971; y < year; ++y) { days += isLeapYear(y) ? 366 : 365; } for (int m = 1; m < month; ++m) { days += daysInMonth(year, m); } days += day; return days; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.