Sometimes, we want to calculate date from today date to 7 days before with JavaScript.
In this article, we’ll look at how to calculate date from today date to 7 days before with JavaScript.
How to calculate date from today date to 7 days before with JavaScript?
To calculate date from today date to 7 days before with JavaScript, we use the Date
constructor.
For instance, we write
const days = 7;
const date = new Date();
const last = new Date(date.getTime() - days * 24 * 60 * 60 * 1000);
to create a new date
object.
And then we call getTime
to get its timestamp in milliseconds.
Then we subtract that by 7 days after converting it to milliseconds.
Finally we put that in the Date
constructor to create a new date 7 days before today.
Conclusion
To calculate date from today date to 7 days before with JavaScript, we use the Date
constructor.