Languages
[Edit]
EN

JavaScript - calculate days difference between two dates

9 points
Created by:
Maison-Humphries
821

In this artcle we would like to show how to calculate days difference between two dates using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const date1 = new Date('2023-10-20');
const date2 = new Date('2023-10-25');

const days = (date2 - date1) / 86400000;  // 86400000 === 1000 * 60 * 60 * 24

console.log(days);  // 6

 

Resusable function

// ONLINE-RUNNER:browser;

const calculateDays = (a, b) => (b - a) / 86400000;


// Usage example:

const date1 = new Date('2023-10-20');
const date2 = new Date('2023-10-25');

const days = calculateDays(date1, date2);

console.log(days);  // 5

Hint: consider to round days using Math.ceil()Math.floor() or Math.round() methods if needed.

 

Universal solution

// ONLINE-RUNNER:browser;

const calculateDays = (a, b) => {
    if (a instanceof Date === false) {
        a = new Date(a);
    }
    if (b instanceof Date === false) {
        b = new Date(b);
    }
    return (b - a) / 86400000;
};


// Usage example:


const a = calculateDays('2023-10-20', '2023-10-25');
const b = calculateDays(1697760000000, 1698192000000);  // as milliseconds since January 1, 1970, 00:00:00 UTC
const c = calculateDays(new Date('2023-10-20'), new Date('2023-10-25'));

console.log(a);  // 5
console.log(b);  // 5
console.log(c);  // 5

 

See also

  1. ISO 8601 - Z meaning in yyyy-MM-ddTHH:mm:ssZ date time format
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join