Katkat

Days Between Two Calendar Dates

OptiverSoftware Engineer · Online Assessment

Last updated

This question evaluates proficiency in date and calendar arithmetic, specifically handling varying month lengths, leap year rules, and computing absolute differences between dates.

Days Between Two Calendar Dates

You are given two dates as strings, each in the format YYYY-MM-DD. Write a function that returns the number of days between the two dates as a non-negative integer (i.e., the absolute difference).

You must account for the varying lengths of months and for leap years. Do not rely on built-in date/calendar libraries — implement the calendar arithmetic yourself. A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years unless they are also divisible by 400 (so 2000 and 2020 are leap years, but 1900 and 2100 are not). In a leap year, February has 29 days; otherwise it has 28.

Input

  • date1: a string in the format YYYY-MM-DD
  • date2: a string in the format YYYY-MM-DD

Both strings are guaranteed to be well-formed, valid calendar dates. The dates may be given in either order (date1 may be before, after, or equal to date2).

Output

Return a single integer: the absolute number of days between the two dates. Two equal dates have a difference of 0.

Examples

Example 1

Input: date1 = "2019-12-31", date2 = "2020-01-15"
Output: 15

From December 31, 2019 to January 15, 2020 is 15 days.

Example 2

Input: date1 = "2020-03-01", date2 = "2020-02-28"
Output: 2

2020 is a leap year, so February 29, 2020 exists: February 28 → February 29 → March 1 is 2 days.

Example 3

Input: date1 = "2021-02-28", date2 = "2021-03-01"
Output: 1

2021 is not a leap year, so February 28 is immediately followed by March 1.

Example 4

Input: date1 = "2020-05-05", date2 = "2020-05-05"
Output: 0

Constraints

  • Each date is a valid calendar date between 1900-01-01 and 2100-12-31 inclusive.
  • The answer fits comfortably in a 32-bit signed integer.