Sometimes, we want to add or subtract dates with JavaScript.
In this article, we’ll look at how to add or subtract dates with JavaScript.
How to add or subtract dates with JavaScript?
To add or subtract dates with JavaScript, we can add or subtract them directly.
For instance, we write
const date1 = new Date(2022, 02, 18);
const date2 = new Date(2022, 02, 20);
const msDiff = date2 - date1;
to create a Date
objects date1
and date2
.
And then we subtract date2
by date1
to get the number of milliseconds difference between them.
date1
and date2
are automatically converted to timestamps before we do the subtraction.
Conclusion
To add or subtract dates with JavaScript, we can add or subtract them directly.