Categories
JavaScript Answers

How to get the difference between two Dates in JavaScript?

Spread the love

Sometimes, we want to get the difference between two Dates in JavaScript.

In this article, we’ll look at how to get the difference between two Dates in JavaScript.

How to get the difference between two Dates in JavaScript?

To get the difference between two Dates in JavaScript, we can subtract 2 dates directly.

For instance, we write

const msMinute = 60 * 1000;
const msDay = 60 * 60 * 24 * 1000;
const a = new Date(2021, 2, 12, 23, 59, 59);
const b = new Date("2022 march 12");

console.log(Math.floor((b - a) / msDay), " full days between");
console.log(Math.floor(((b - a) % msDay) / msMinute), " full minutes between");

to subtract b from a to get the difference of their timestamps in milliseconds.

Then we get the floor of the quotient of their difference divided by msDay to get the days difference.

And then we get the floor of the quotient of (b - a) % msDay) divided by msMinute to get the minute difference between b and a‘s times.

Conclusion

To get the difference between two Dates in JavaScript, we can subtract 2 dates directly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *