Sometimes, we want to get last week’s date with JavaScript.
In this article, we’ll look at how to get last week’s date with JavaScript.
How to get last week’s date with JavaScript?
To get last week’s date with JavaScript, we can get the timestamp of the original date and subtract 7 * 24 * 60 * 60 * 1000
from it.
For instance, we write:
const firstDay = new Date(2022, 1, 2)
const previousWeek = new Date(firstDay.getTime() - 7 * 24 * 60 * 60 * 1000);
console.log(previousWeek)
to create the firstDay
date.
Then we get the timestamp of firstDay
in milliseconds with getTime
.
And then we subtract 7 days from firstDay
in milliseconds and create a new Date
instance from the returned timestamp.
Therefore, previousWeek
is Wed Jan 26 2022 00:00:00 GMT-0800 (Pacific Standard Time)
.
Conclusion
To get last week’s date with JavaScript, we can get the timestamp of the original date and subtract 7 * 24 * 60 * 60 * 1000
from it.