Talentd
FleetCode
Make and follow sheets.Sign in

Number of Days Between Two Dates solution and explanation

EasyMathString6 min read53.7% acceptanceUpdated 9 Apr 2026
Leetcode 1360. Number of Days Between Two Dates Python SolutionsTechZoo · 3:03 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. Leetcode 1360. Number of Days Between Two Dates Python SolutionsTechZoo · 3:03 · 1K views
  2. LeetCode 1360 - Number of Days Between Two Dates: A Microsoft JourneyThe Lofi Dev · 2:49 · 1K views
  3. Leetcode | Easy | 1360. Number of Days Between Two Dates | Time complexity: O(1) | JavascriptSoftware Interviews Prep · 4:30 · 734 views
  4. #LeetCode 1360 | Number of Days Between Two Dates #JavaSleepy Cracker · 6:26 · 666 views
  5. Number of Days Between Two Dates | Leetcode - 1360 | Approach + Code with explanation.Pirai's Academy · 12:17 · 558 views
  6. Vol34 - Leetcode - Problem 1360 - Number of days between two dates - Golang - Phỏng vấn - Thuật toánYuh lập trình viên · 8:58 · 253 views
  7. Leetcode1360 Number of Days Between Two Dates 日期之間隔幾天 python3Robotics Fans · 2:51 · 110 views
  8. Solving Number of Days Between Two Dates Leetcode Problem with PHPAmr Elsayed · 6:21 · 85 views
  9. Day 743: LeetCode Problem 1360. Number of Days Between Two Dates -SwiftiOSxBank · 6:10 · 23 views
  10. LeetCode 1360: Number of Days Between Two DatesAlitaCode · 26:16 · 9 views

The problem

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.

from datetime import datetime

def days_between_dates(date1, date2):
    d1 = datetime.strptime(date1, "%Y-%m-%d")
    d2 = datetime.strptime(date2, "%Y-%m-%d")
    return abs((d2 - d1).days)

# Example usage
date1 = "2019-06-29"
date2 = "2019-06-30"
print(days_between_dates(date1, date2))
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DaysBetweenDates {
    public static long daysBetweenDates(String date1, String date2) {
        LocalDate d1 = LocalDate.parse(date1);
        LocalDate d2 = LocalDate.parse(date2);
        return Math.abs(ChronoUnit.DAYS.between(d1, d2));
    }

    public static void main(String[] args) {
        String date1 = "2019-06-29";
        String date2 = "2019-06-30";
        System.out.println(daysBetweenDates(date1, date2));
    }
}
#include <iostream>
#include <sstream>
#include <ctime>
#include <cmath>

int daysBetweenDates(const std::string& date1, const std::string& date2) {
    std::tm tm1 = {}, tm2 = {};
    std::istringstream ss1(date1), ss2(date2);
    ss1 >> std::get_time(&tm1, "%Y-%m-%d");
    ss2 >> std::get_time(&tm2, "%Y-%m-%d");
    auto time1 = std::mktime(&tm1);
    auto time2 = std::mktime(&tm2);
    return std::abs(std::difftime(time1, time2)) / (60 * 60 * 24);
}

int main() {
    std::string date1 = "2019-06-29";
    std::string date2 = "2019-06-30";
    std::cout << daysBetweenDates(date1, date2) << std::endl;
    return 0;
}
function daysBetweenDates(date1, date2) {
    const d1 = new Date(date1);
    const d2 = new Date(date2);
    const diffTime = Math.abs(d2 - d1);
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}

// Example usage
const date1 = "2019-06-29";
const date2 = "2019-06-30";
console.log(daysBetweenDates(date1, date2));
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int daysBetweenDates(const char *date1, const char *date2) {
    struct tm tm1 = {0}, tm2 = {0};
    strptime(date1, "%Y-%m-%d", &tm1);
    strptime(date2, "%Y-%m-%d", &tm2);
    time_t time1 = mktime(&tm1);
    time_t time2 = mktime(&tm2);
    double difference = difftime(time1, time2);
    return abs(difference) / (60 * 60 * 24);
}

int main() {
    const char *date1 = "2019-06-29";
    const char *date2 = "2019-06-30";
    printf("%d\n", daysBetweenDates(date1, date2));
    return 0;
}
using System;

public class DaysBetweenDates {
    public static int DaysBetweenDates(string date1, string date2) {
        DateTime d1 = DateTime.Parse(date1);
        DateTime d2 = DateTime.Parse(date2);
        return Math.Abs((d2 - d1).Days);
    }

    public static void Main() {
        string date1 = "2019-06-29";
        string date2 = "2019-06-30";
        Console.WriteLine(DaysBetweenDates(date1, date2));
    }
}

Python's datetime module provides functionalities to parse date strings and compute differences. Here, strptime is used to parse the strings, and subtraction of datetime objects gives a timedelta object, whose days attribute gives the result.

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.

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

def days_in_month(year, month):
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if month == 2 and is_leap_year(year):
        return 29
    return days[month - 1]

def days_from_epoch(date):
    year, month, day = map(int, date.split('-'))
    days = 0
    for y in range(1971, year):
        days += 366 if is_leap_year(y) else 365
    for m in range(1, month):
        days += days_in_month(year, m)
    days += day - 1
    return days

def days_between_dates(date1, date2):
    d1 = days_from_epoch(date1)
    d2 = days_from_epoch(date2)
    return abs(d2 - d1)

# Example usage
date1 = "2019-06-29"
date2 = "2019-06-30"
print(days_between_dates(date1, date2))
public class DaysBetweenDates {

    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }

    public static int daysInMonth(int year, int month) {
        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if (month == 2 && isLeapYear(year)) {
            return 29;
        }
        return days[month - 1];
    }

    public static int daysFromEpoch(String date) {
        String[] parts = date.split("-");
        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        int day = Integer.parseInt(parts[2]);
        int days = 0;
        for (int y = 1971; y < year; y++) {
            days += isLeapYear(y) ? 366 : 365;
        }
        for (int m = 1; m < month; m++) {
            days += daysInMonth(year, m);
        }
        days += day - 1;
        return days;
    }

    public static int daysBetweenDates(String date1, String date2) {
        int d1 = daysFromEpoch(date1);
        int d2 = daysFromEpoch(date2);
        return Math.abs(d2 - d1);
    }

    public static void main(String[] args) {
        String date1 = "2019-06-29";
        String date2 = "2019-06-30";
        System.out.println(daysBetweenDates(date1, date2));
    }
}
#include <iostream>
#include <cstdlib>

bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int daysInMonth(int year, int month) {
    int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month == 2 && isLeapYear(year)) 
        return 29;
    return days[month - 1];
}

int daysFromEpoch(const std::string &date) {
    int year, month, day;
    sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day);
    int days = 0;
    for (int y = 1971; y < year; ++y) {
        days += isLeapYear(y) ? 366 : 365;
    }
    for (int m = 1; m < month; ++m) {
        days += daysInMonth(year, m);
    }
    days += day - 1;
    return days;
}

int daysBetweenDates(const std::string &date1, const std::string &date2) {
    int d1 = daysFromEpoch(date1);
    int d2 = daysFromEpoch(date2);
    return abs(d2 - d1);
}

int main() {
    std::string date1 = "2019-06-29";
    std::string date2 = "2019-06-30";
    std::cout << daysBetweenDates(date1, date2) << std::endl;
    return 0;
}
function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

function daysInMonth(year, month) {
    const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (month === 2 && isLeapYear(year)) return 29;
    return days[month - 1];
}

function daysFromEpoch(date) {
    const [year, month, day] = date.split('-').map(Number);
    let days = 0;
    for (let y = 1971; y < year; y++) {
        days += isLeapYear(y) ? 366 : 365;
    }
    for (let m = 1; m < month; m++) {
        days += daysInMonth(year, m);
    }
    days += day - 1;
    return days;
}

function daysBetweenDates(date1, date2) {
    const d1 = daysFromEpoch(date1);
    const d2 = daysFromEpoch(date2);
    return Math.abs(d2 - d1);
}

// Example usage
const date1 = "2019-06-29";
const date2 = "2019-06-30";
console.log(daysBetweenDates(date1, date2));
#include <stdio.h>
#include <stdlib.h>

int isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int daysInMonth(int year, int month) {
    static int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    if (month == 2 && isLeapYear(year)) {
        return 29;
    }
    return days[month - 1];
}

int daysFromEpoch(const char *date) {
    int year, month, day;
    sscanf(date, "%d-%d-%d", &year, &month, &day);
    int days = 0;
    for (int y = 1971; y < year; y++) {
        days += isLeapYear(y) ? 366 : 365;
    }
    for (int m = 1; m < month; m++) {
        days += daysInMonth(year, m);
    }
    days += day - 1;
    return days;
}

int daysBetweenDates(const char *date1, const char *date2) {
    int d1 = daysFromEpoch(date1);
    int d2 = daysFromEpoch(date2);
    return abs(d2 - d1);
}

int main() {
    const char *date1 = "2019-06-29";
    const char *date2 = "2019-06-30";
    printf("%d\n", daysBetweenDates(date1, date2));
    return 0;
}
using System;

public class ManualDaysBetweenDates {
    public static bool IsLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }

    public static int DaysInMonth(int year, int month) {
        int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        if (month == 2 && IsLeapYear(year)) return 29;
        return days[month - 1];
    }

    public static int DaysFromEpoch(string date) {
        string[] parts = date.Split('-');
        int year = int.Parse(parts[0]);
        int month = int.Parse(parts[1]);
        int day = int.Parse(parts[2]);
        int days = 0;
        for (int y = 1971; y < year; y++) {
            days += IsLeapYear(y) ? 366 : 365;
        }
        for (int m = 1; m < month; m++) {
            days += DaysInMonth(year, m);
        }
        days += day - 1;
        return days;
    }

    public static int DaysBetweenDates(string date1, string date2) {
        int d1 = DaysFromEpoch(date1);
        int d2 = DaysFromEpoch(date2);
        return Math.Abs(d2 - d1);
    }

    public static void Main() {
        string date1 = "2019-06-29";
        string date2 = "2019-06-30";
        Console.WriteLine(DaysBetweenDates(date1, date2));
    }
}

For Python, similar to other languages, the function manually calculates days by checking leap years and iterating through possible days in intervening months and years, starting from a fixed point in time.

Complexity

Time Complexity: O(N); 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).

function daysBetweenDates(date1: string, date2: string): number {
    return Math.abs(calcDays(date1) - calcDays(date2));
}

function isLeapYear(year: number): boolean {
    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}

function daysOfMonth(year: number, month: number): number {
    const days = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return days[month - 1];
}

function calcDays(date: string): number {
    let days = 0;
    const [year, month, day] = date.split('-').map(Number);
    for (let y = 1971; y < year; ++y) {
        days += isLeapYear(y) ? 366 : 365;
    }
    for (let m = 1; m < month; ++m) {
        days += daysOfMonth(year, m);
    }
    days += day - 1;
    return days;
}
func daysBetweenDates(date1 string, date2 string) int {
	return abs(calcDays(date1) - calcDays(date2))
}

func isLeapYear(year int) bool {
	return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}

func daysInMonth(year, month int) int {
	days := [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
	if isLeapYear(year) {
		days[1] = 29
	}
	return days[month-1]
}

func calcDays(date string) int {
	year, _ := strconv.Atoi(date[:4])
	month, _ := strconv.Atoi(date[5:7])
	day, _ := strconv.Atoi(date[8:])
	days := 0
	for y := 1971; y < year; y++ {
		days += 365
		if isLeapYear(y) {
			days++
		}
	}
	for m := 1; m < month; m++ {
		days += daysInMonth(year, m)
	}
	days += day
	return days
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
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); Space Complexity: O(1)

Mathematics–

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

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).

Comments

Now write it yourselfClose this page and solve Number of Days Between Two Dates in the editor, without looking.
Practise Number of Days Between Two Dates