Number of Days Between Two Dates - Problem

You're given two dates in string format as YYYY-MM-DD and need to calculate the absolute number of days between them.

This is a fundamental date calculation problem that appears frequently in real-world applications like subscription billing, project management, and age calculations.

Goal: Calculate the difference in days between two valid dates.

Input: Two date strings in format "YYYY-MM-DD"

Output: A single integer representing the absolute number of days between the dates

Example: Between "2020-01-15" and "2019-12-31", there are 15 days.

Input & Output

example_1.py โ€” Basic Date Difference
$ Input: date1 = "2019-06-29", date2 = "2019-06-30"
โ€บ Output: 1
๐Ÿ’ก Note: The difference between June 29, 2019 and June 30, 2019 is exactly 1 day. Simple consecutive date calculation.
example_2.py โ€” Cross-Year Calculation
$ Input: date1 = "2020-01-15", date2 = "2019-12-31"
โ€บ Output: 15
๐Ÿ’ก Note: From Dec 31, 2019 to Jan 15, 2020: 15 days total. This tests year boundary crossing and ensures we return absolute difference.
example_3.py โ€” Same Date Edge Case
$ Input: date1 = "2020-02-29", date2 = "2020-02-29"
โ€บ Output: 0
๐Ÿ’ก Note: When both dates are identical, the difference is 0. This also tests leap year date handling (Feb 29).

Constraints

  • The given dates are valid dates between the years 1971 and 2100
  • Dates are given in format YYYY-MM-DD
  • Both dates will be valid according to the Gregorian calendar
  • Years from 1971 to 2100 inclusively

Visualization

Tap to expand
Days Between Dates - Timeline VisualizationYear 1 ADModern Times2019-12-31Day 737,4242020-01-15Day 737,439737,439 - 737,424 = 15 daysMathematical Approach:1. Convert 2019-12-31 โ†’ 737,424 days since epoch2. Convert 2020-01-15 โ†’ 737,439 days since epoch3. Calculate |737,439 - 737,424| = 15โœ“ Result: 15 days in O(1) time!
Understanding the Visualization
1
Reference Point
Establish year 1 AD as our reference epoch (day 0)
2
Convert First Date
Calculate total days from epoch to first date
3
Convert Second Date
Calculate total days from epoch to second date
4
Find Difference
Subtract the two values and take absolute difference
Key Takeaway
๐ŸŽฏ Key Insight: Converting dates to a numerical representation (days since epoch) transforms the problem from iterative counting to simple arithmetic subtraction.
Asked in
Google 23 Amazon 18 Microsoft 15 Apple 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen