On this page
A fragment of the calendar with marked two days

Get days between two dates in JavaScript

Calculate days between two dates in JavaScript with a simple function. Learn how to handle DST issues and get accurate results.

To get the number of days between two given dates, you can do that by converting them to UTC timestamps and then computing the difference in days based on the millisecond difference.

JavaScript code for calculating days between two dates

A simple JavaScript code to get the number of days between two given dates is:

Get days between two dates in JavaScript
function getDaysBetweenTwoDates(firstDateInISO, secondDateInISO): number {
    const startDate = new Date(firstDateInISO);
    const endDate = new Date(secondDateInISO);

    const firstDate = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
    const secondDate = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());

    return Math.abs((firstDate.valueOf() - secondDate.valueOf()) / (24 * 60 * 60 * 1000));

Simply subtracting the dates will not work over the Daylight Savings Time boundary (for example, April 1 to April 30 or October 1 to October 31). This reduces all of the hours to ensure you get a day and solves any DST issues by using UTC.

Code explanation

Let’s break down the code:

  • Input Parameters:

    • firstDateInISO: A string representing the first date in ISO format.
    • secondDateInISO: A string representing the second date in ISO format.
  • Date Conversion:

    • The code first converts the input date strings into Date objects using the new Date() constructor.
    • It then extracts the year, month, and date components from these Date objects using getFullYear(), getMonth(), and getDate() methods.
  • Date Comparison:

    • The code converts the extracted year, month, and date components of both dates into UTC timestamps using Date.UTC().
    • These UTC timestamps are then used to calculate the difference in milliseconds between the two dates by subtracting the UTC timestamps and taking the absolute value.
  • Calculating Days:

    • The code divides the time difference in milliseconds by the total number of milliseconds in a day (24 hours * 60 minutes * 60 seconds * 1000 milliseconds) to get the number of days between the two dates.
    • The result is returned as a number representing the absolute difference in days between the two input dates.

Practical example with unit tests for calculating days between dates

Here is a workable example that calculates days between two days and includes unit tests.

Related posts


Leave a Reply

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)