Katkat

Count the Days Between Two Dates

OptiverSoftware Engineer · Online Assessment

Last 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 in YYYY-MM-DD format.
  • date2: a string in YYYY-MM-DD format.

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

date1date2OutputExplanation
2019-06-292019-06-301Consecutive days.
2019-12-312020-01-1515Crosses a year boundary.
2020-02-282020-03-0122020 is a leap year, so February 29 lies between them.
2019-02-282019-03-0112019 is not a leap year.
2021-07-042021-07-040Same date.

Constraints

  • 1900-01-01 <= date1, date2 <= 2100-12-31
  • Both inputs are valid dates in YYYY-MM-DD format.
  • No date/time library calls are allowed; leap-year handling must be implemented from the rules above.