Count the Days Between Two Dates
OptiverSoftware Engineer · Online AssessmentLast updated
This question evaluates date arithmetic, calendar logic, string parsing, and correct leap-year handling as implementation competencies. It is commonly asked to assess algorithmic correctness and edge-case handling across month, year, and leap boundaries, falls under the Coding & Algorithms domain (date/calendar problems), and targets practical application rather than purely conceptual understanding.
Count the Days Between Two Dates
You are given two calendar dates as strings in YYYY-MM-DD format. Return the number of days between them as a non-negative integer.
You must compute the result without using any built-in date/time or calendar library (e.g., no datetime, java.time, Date, or similar). The only calendar knowledge you may rely on is the standard Gregorian calendar rules given below. Assume a helper that returns the number of days in a given month is something you write yourself.
Calendar rules
- Months have the usual lengths: January 31, February 28 (29 in a leap year), March 31, April 30, May 31, June 30, July 31, August 31, September 30, October 31, November 30, December 31.
- A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. So 2000 and 2024 are leap years; 1900 and 2100 are not.
Input
date1: a string inYYYY-MM-DDformat.date2: a string inYYYY-MM-DDformat.
Both dates are guaranteed to be valid calendar dates between 1900-01-01 and 2100-12-31 inclusive. The dates may be given in either order (date1 is not necessarily earlier than date2).
Output
Return a single integer: the absolute difference in days between the two dates. If the dates are equal, return 0.
Examples
| date1 | date2 | Output | Explanation |
|---|---|---|---|
2019-06-29 | 2019-06-30 | 1 | Consecutive days. |
2019-12-31 | 2020-01-15 | 15 | Crosses a year boundary. |
2020-02-28 | 2020-03-01 | 2 | 2020 is a leap year, so February 29 lies between them. |
2019-02-28 | 2019-03-01 | 1 | 2019 is not a leap year. |
2021-07-04 | 2021-07-04 | 0 | Same date. |
Constraints
1900-01-01 <= date1, date2 <= 2100-12-31- Both inputs are valid dates in
YYYY-MM-DDformat. - No date/time library calls are allowed; leap-year handling must be implemented from the rules above.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.