Sometimes, we want to get the difference between dates in JavaScript.
In this article, we’ll look at how to get the difference between dates in JavaScript.
How to get the difference between dates in JavaScript?
To get the difference between dates in JavaScript, we can subtract 2 date objects directly.
For instance, we write
const a = new Date();
const b = new Date(2022, 0, 1, 0, 0, 0, 0);
const d = b - a;
to define the a
and b
date objects.
Then we subtract b
by a
to get their difference.
They’ll be converted to timestamps in milliseconds before the difference is computed, so d
would be a timestamp in milliseconds.
Conclusion
To get the difference between dates in JavaScript, we can subtract 2 date objects directly.