Sometimes, we want to calculate the date that is 2 days ago with JavaScript.
In this article, we’ll look at how to calculate the date that is 2 days ago with JavaScript.
How to calculate the date that is 2 days ago with JavaScript?
To calculate the date that is 2 days ago with JavaScript, we use the getDate
and setDate
methods.
For instance, we write
const d = new Date();
d.setDate(d.getDate() - 2);
console.log(d.toString());
to create the date d
with the current date and time.
Then we get the date of the current date with getDate
and subtract 2 from it to get the date 2 days ago.
And then we use the difference as the argument for setDate
.
Finally, we call toString
to return a date string version of d
.
Conclusion
To calculate the date that is 2 days ago with JavaScript, we use the getDate
and setDate
methods.