Magicsheet logo

Number of Days Between Two Dates

Easy
38.7%
Updated 6/1/2025

Number of Days Between Two Dates

What is this problem about?

The Number of Days Between Two Dates problem asks you to compute the absolute difference in days between two date strings in "YYYY-MM-DD" format. This requires handling leap years correctly and converting dates to a total day count from a common epoch. This coding problem tests math and date arithmetic implementation skills.

Why is this asked in interviews?

Microsoft, Meta, Amazon, and Google ask this to test careful date arithmetic without using library functions. It validates knowledge of leap year rules (divisible by 4, except centuries unless divisible by 400) and the ability to implement a complete date-to-days conversion from scratch. The math and string interview pattern is demonstrated.

Algorithmic pattern used

Convert both dates to days from epoch + subtract. Convert "YYYY-MM-DD" to total days since a base date (e.g., year 1, day 1). For each date: compute days from full years (accounting for leap years), add days from full months in the current year, add remaining days. Return the absolute difference.

Example explanation

Date 1: "2019-06-29", Date 2: "2019-06-30". Days from epoch for both differ by exactly 1. Result = 1 day.

Date 1: "2000-01-01", Date 2: "2000-03-01" (2000 is a leap year): Jan=31, Feb=29 (leap year), so March 1 is day 60+1=61. Difference from Jan 1 = 60 days.

Common mistakes candidates make

  • Wrong leap year rule: year divisible by 4 is a leap year, EXCEPT centuries (divisible by 100) are NOT, EXCEPT if also divisible by 400 they ARE.
  • Incorrect month lengths for February in leap vs non-leap years.
  • Off-by-one when summing days (days in a month vs days elapsed).
  • Not taking absolute value of the difference.

Interview preparation tip

Date arithmetic from scratch requires correctly implementing the leap year formula: (year % 4 == 0 and year % 100 != 0) or year % 400 == 0. Memorize the days per month array and remember February has 28 or 29 days. Practice computing "days since year 1, January 1" for a given date — this conversion is the core building block for all calendar arithmetic problems. Always test with boundary cases: Feb 28/29, year 2000, year 1900.

Similar Questions