Skip to main content

Number of Days Between Two Dates - Solution & Explanation

EasyMathString21 min readAsked at: Amazon, Meta, Google +1
Practice this problem

Problem Statement

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

 

Example 1:

Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1

Example 2:

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

 

Constraints:

  • The given dates are valid dates between the years 1971 and 2100.

Approach Overview

Problem Overview: You receive two dates in YYYY-MM-DD format and must return the absolute number of days between them. The task is essentially converting both dates into comparable day counts and computing the difference.

Approach 1: Using Built-in Date Libraries (O(1) time, O(1) space)

Most languages provide date utilities that already handle calendar rules such as leap years and month lengths. Parse both strings into date objects using built-in libraries like datetime in Python, LocalDate in Java, or Date in JavaScript. Subtract the two date objects to obtain the difference in days, then return the absolute value. The heavy lifting—parsing, leap-year handling, and calendar arithmetic—is handled internally by the library. This approach is short, reliable, and preferred in production code.

The algorithm simply performs parsing followed by a subtraction operation. Time complexity is O(1) because the input size is fixed and the date arithmetic runs in constant time. Space complexity is also O(1). This approach fits well when standard libraries are allowed and reduces the risk of calendar-related bugs.

Approach 2: Manual Date Calculation (O(1) time, O(1) space)

If library utilities are restricted, compute the difference manually. Split each date string into year, month, and day components. Convert each date into the total number of days since a fixed reference (for example, 1971-01-01 or 0000-01-01). The conversion works by adding days from previous years, accounting for leap years, then adding days from the months in the current year, and finally the day of the month.

Leap years follow the rule: divisible by 4 but not by 100 unless also divisible by 400. Use an array representing days in each month and add one extra day to February during leap years. After converting both dates into total day counts, subtract them and take the absolute value. This approach demonstrates understanding of calendar arithmetic and is commonly expected in coding interviews that test math reasoning and string parsing.

Manual conversion still runs in O(1) time since the number of months and years processed is bounded. Space complexity remains O(1). The complexity appears constant because the input format is fixed length.

Recommended for interviews: Start by explaining the manual conversion approach. It shows you understand leap years, month lengths, and how to convert a date into a numeric representation. After that, mention that real-world code typically relies on built-in date libraries for reliability and readability. Demonstrating both approaches shows strong problem-solving fundamentals and practical engineering judgment.

Approach 1: Using Built-in Date Libraries

This approach involves using the built-in date handling libraries in various programming languages. These libraries simplify the task of parsing date strings and calculating differences between dates by providing specialized functions.

In C, strptime and mktime functions are used to convert date strings into time structures and then into time_t objects for comparison. The function difftime calculates the difference in seconds, which is then converted into days by dividing by the number of seconds in a day.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(1); Space Complexity: O(1)

Try this approach in the editor →

Approach 2: Manual Date Calculation

This approach involves manually parsing the date strings and calculating the number of days between the two dates using a custom algorithm. This method is beneficial in educational contexts to understand date manipulations without relying on library functions.

This solution calculates the number of days from a fixed date (epoch) by manually iterating over the years, months, and days. It accounts for leap years and differences in month lengths to ensure correctness.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N), where N is the difference in years from the epoch (1971 to 2100); Space Complexity: O(1)

Try this approach in the editor →

Approach 3: Mathematics

First, we define a function isLeapYear(year) to determine whether the given year year is a leap year. If it is a leap year, return true, otherwise return false.

Next, we define another function daysInMonth(year, month) to calculate the total number of days in the given year year and month month. We can use an array days to store the number of days in each month, where days[1] represents the number of days in February. If it is a leap year, it is 29 days, otherwise it is 28 days.

Then, we define another function calcDays(date) to calculate the number of days from the given date date to 1971-01-01. We can use date.split("-") to split the date date into year year, month month, and day day by -. Then we can use a loop to calculate the total number of days from 1971 to year, then calculate the total number of days from January to month, and finally add day days.

Finally, we only need to return the absolute value of calcDays(date1) - calcDays(date2).

The time complexity is O(y + m), where y represents the number of years from the given date to 1971-01-01, and m represents the number of months of the given date. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using Built-in Date Libraries

Time Complexity: O(1); Space Complexity: O(1)

Manual Date Calculation

Time Complexity: O(N), where N is the difference in years from the epoch (1971 to 2100); Space Complexity: O(1)

Mathematics—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Using Built-in Date LibrariesO(1)O(1)Best for production code when language date utilities are allowed
Manual Date CalculationO(1)O(1)When libraries are restricted or interviews test calendar math understanding

Video Solution

Leetcode 1360. Number of Days Between Two Dates Python Solutions • TechZoo • 1,566 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Number of Days Between Two Dates easy or hard?
LeetCode classifies this problem as Easy. The main challenge is correctly handling leap years and month lengths if implementing the manual calculation approach.
Number of Days Between Two Dates Python/Java solution
In Python, parse the strings using datetime.strptime and subtract the resulting date objects to obtain a timedelta, then return abs(delta.days). In Java, use LocalDate.parse and ChronoUnit.DAYS.between to compute the difference. Both implementations run in O(1) time.
How to solve Number of Days Between Two Dates in O(1)?
Convert both dates into a total day count from a fixed reference date. Add days from previous years (including leap years), add days from previous months in the current year, then add the day value. Compute the absolute difference between the two totals. Since the number of months and calculations is constant, the complexity is O(1).
What is the best approach for Number of Days Between Two Dates?
The most practical approach uses built-in date libraries such as Python's datetime, Java's LocalDate, or JavaScript's Date. Parse both YYYY-MM-DD strings into date objects and subtract them to get the day difference. This runs in O(1) time and avoids manual leap-year and month calculations.
Is Number of Days Between Two Dates asked at Google/Amazon/Meta?
Date arithmetic and calendar calculation problems appear in interviews at companies like Google and Amazon because they test edge-case handling and logical reasoning. Variations include computing day differences, validating dates, or implementing calendar utilities.
What data structure is used in Number of Days Between Two Dates?
The solution mainly relies on arrays and simple arithmetic. An array storing the number of days in each month helps when performing manual calculations, while string parsing extracts the year, month, and day values from the input.
What is the time complexity of Number of Days Between Two Dates?
Both common approaches run in O(1) time because the input format is fixed-length and the operations involve constant-size calculations. Parsing the date string and computing the difference between two date values does not depend on input size. Space complexity is also O(1).

Ready to solve this problem?

Practice Number of Days Between Two Dates with our built-in code editor and test cases.

Practice on FleetCode