Skip to content
← All posts

Number of Days Between Two Dates: Date-to-Day Conversion

6 min read
leetcodeproblemeasymathstrings

Given two date strings in the format YYYY-MM-DD, return the number of days between the two dates. For example, daysBetweenDates("2020-01-15", "2019-12-31") returns 15.

This is LeetCode 1360: Number of Days Between Two Dates, and it is one of the cleanest problems for learning date math from scratch. No date libraries, no built-in parsing. Just arithmetic and a careful leap year check.

2020-01-15date12020-03-15date260 days
Convert each date to a total day count from a reference point, then take the absolute difference. |days(date2) - days(date1)| = 60.

Why this problem matters

Date arithmetic shows up everywhere in software engineering, from scheduling systems to financial calculations. But most of us reach for a library without thinking about what it does under the hood. This problem forces you to implement the fundamentals yourself: leap year detection, cumulative month offsets, and converting a calendar date to a flat day count. Once you understand these building blocks, you will also understand why date bugs happen in production code and how to avoid them.

The technique here, converting two structured values into a common numeric space and then comparing, is a pattern that goes well beyond dates. You will see the same idea in coordinate geometry, unit conversion problems, and encoding schemes like Excel column numbers.

The key insight

Instead of trying to count days directly from one date to another (which requires handling month boundaries, leap years mid-range, and edge cases for crossing year boundaries), convert each date independently to a total number of days from some fixed reference point. Then the answer is simply the absolute difference between the two totals.

The conversion works like this:

  1. Count all the days contributed by full years (year * 365).
  2. Add the leap days that occurred in those years.
  3. Add the cumulative days for completed months in the current year.
  4. Add the day of the month.

The leap year rule: a year is a leap year if it is divisible by 4, but not by 100, unless it is also divisible by 400. So 2000 is a leap year, 1900 is not, and 2020 is.

The solution

def daysBetweenDates(date1: str, date2: str) -> int:
    def to_days(date: str) -> int:
        y, m, d = map(int, date.split("-"))
        months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        days = 365 * y + d
        for i in range(1, m):
            days += months[i]
        if m <= 2:
            y -= 1
        days += y // 4 - y // 100 + y // 400
        return days

    return abs(to_days(date1) - to_days(date2))

The function to_days converts a single date string into an absolute day count. It splits the string on "-" to get the year, month, and day as integers.

The base count starts at 365 * y + d, accounting for full years and the current day of the month. Then it adds the number of days in all completed months before month m using a prefix sum over the months array (which uses 28 for February as the non-leap default).

The leap day adjustment is the clever part. If the current month is January or February, we decrement y by one before computing leap days. Why? Because if we are still in Jan or Feb, we have not yet reached the leap day (Feb 29) of the current year, so we should not count it. The formula y // 4 - y // 100 + y // 400 counts the total number of leap years up to and including year y, following the standard leap year rules.

Finally, abs(to_days(date1) - to_days(date2)) gives the answer regardless of which date comes first.

The if m <= 2: y -= 1 trick is the key to clean leap year handling. By treating January and February as belonging to the "previous year" for leap day counting purposes, you avoid a separate branch for whether the current year is a leap year and whether you have passed February yet. This is a well-known technique in calendar algorithms.

Visual walkthrough

Let's trace through daysBetweenDates("2020-01-15", "2020-03-15") step by step. Watch how each date converts to a single integer, and then the difference gives us the answer.

Step 1: Parse both date strings

date12020-01-15date22020-03-15

Split each string on "-" to extract year, month, and day as integers.

Step 2: Convert date1 to total days

year contribution365 * 2020 = 737300leap day adjustment+ 490 leap daysmonth days (Jan)+ 0 (before Jan)day of month+ 15total days(date1)737805

Count all days from a reference point: full years, leap days, month offsets, and day within the month.

Step 3: Convert date2 to total days

year contribution365 * 2020 = 737300leap day adjustment+ 490 leap daysmonth days (Jan+Feb)+ 31 + 29 = 60day of month+ 15total days(date2)737865

Same process for date2. Note Feb has 29 days in 2020 because 2020 is a leap year.

Step 4: Take the absolute difference

days(date1)737805days(date2)737865|date2 - date1|60

The answer is |737865 - 737805| = 60 days between the two dates.

The first date lands in January, so we decrement the year before computing leap days (treating it as "2019" for leap purposes). The second date is in March, so we use the full year 2020 and include the leap day for 2020. The difference in month contributions (0 for Jan vs 60 for Jan+Feb in a leap year) plus the leap day adjustment produces the correct gap of 60 days.

Complexity analysis

ApproachTimeSpace
Date-to-day conversionO(1)O(1)

Time is O(1). The month loop runs at most 12 iterations, and every other operation is constant. The input size is fixed (two date strings of length 10).

Space is O(1). We use a fixed-size array of 13 month lengths and a few integer variables. Nothing scales with input.

The building blocks

1. Leap year detection

The formula y // 4 - y // 100 + y // 400 counts the number of leap years from year 1 through year y. This uses inclusion-exclusion: start with every fourth year, subtract every hundredth year (which are not leap years), and add back every four-hundredth year (which are). You will see this exact formula in any problem that involves calendar calculations.

2. Cumulative month-day offset

The array [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] holds the number of days in each month (with February as 28). Summing months 1 through m-1 gives the total days elapsed before the current month. This is the same prefix sum technique you use in range-sum queries, just applied to a fixed 12-element array.

Edge cases

  • Same date: to_days returns the same value for both, so abs(0) = 0. Correct.
  • Dates spanning a leap year boundary: The formula handles this automatically. If one date is in Feb 2020 and the other is in Mar 2020, the leap day on Feb 29 is correctly included.
  • Century years: 1900 is not a leap year (divisible by 100 but not 400). 2000 is a leap year (divisible by 400). The formula accounts for both.
  • Dates in different order: The abs() call means you do not need to worry about which date comes first.
  • January and February dates: The if m <= 2: y -= 1 adjustment ensures leap days are not counted prematurely.

From understanding to recall

The solution fits in about ten lines of code, and once you see the to_days conversion, the logic clicks. But reproducing it under interview pressure is harder than it looks. The leap year formula has three terms. The month-offset loop has an off-by-one opportunity. The m <= 2 adjustment is easy to forget.

Spaced repetition closes that gap. You write the to_days function from memory, check against the reference, and repeat at increasing intervals. After a few rounds, the leap year formula and the month adjustment are automatic. When you see a date problem in an interview, you reach for the conversion pattern without hesitating.

Related posts

  • Reverse Integer - Another math problem where you process a value digit by digit using modular arithmetic
  • Excel Sheet Column Number - Converting between two numeric representations using positional arithmetic, the same "map to a number and compute" pattern
  • Palindrome Number - Pure math approach to a problem that tempts you to use string conversion

CodeBricks breaks Number of Days Between Two Dates into its leap year detection and date-to-day conversion building blocks, then drills them independently with spaced repetition. You type each piece from scratch until the pattern is automatic. When a date math problem shows up in your interview, you do not think about it. You just write it.