Last updated: Mar 5, 2024
Reading timeยท2 min

To get last week's date, use the Date() constructor to create a new date,
passing it the year, month and day of the month - 7 to get the date of a week
ago.
function getLastWeeksDate() { const now = new Date(); return new Date( now.getFullYear(), now.getMonth(), now.getDate() - 7, ); } // ๐๏ธ Wed Jul 19 2023 00:00:00 console.log(getLastWeeksDate()); // ๐๏ธ Wed Jul 26 2023 10:46:35 console.log(new Date());

We used the following 3 Date related methods:
Date.getFullYear() method - returns a four-digit number representing the year that corresponds to a date.
Date.getMonth() - returns an
integer between 0 (January) and 11 (December) and represents the month for
a given date. Yes, unfortunately, the getMonth method is off by 1.
Date.getDate() - returns an
integer between 1 and 31 representing the day of the month for a specific
date.
By
subtracting 7 days from the current date,
we get last week's date.
Date() object in JavaScript automatically rolls over or back and will adjust the month and/or year if the days of the month value is negative.If you want to preserve the time, you can convert 1 week to milliseconds and
subtract the result from the milliseconds of the current date.
function getLastWeeksDate() { const now = new Date(); return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); } // ๐๏ธ Wed Jul 19 2023 10:47:53 console.log(getLastWeeksDate()); // ๐๏ธ Wed Jul 26 2023 10:47:53 console.log(new Date());

The getTime() method returns the number of milliseconds since the Unix epoch for the specific Date.
You can also take a Date object as a parameter in the function to get the date
of the previous week for any Date.
You can learn more about the related topics by checking out the following tutorials: