Borislav Hadzhiev
Sun Jan 16 2022·2 min read
Photo by Giau Tran
To get last week's date, use the Date()
constructor to create a new date,
passing it the year, month and the 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); } // 👇️ Sun Jan 09 2022 00:00:00 console.log(getLastWeeksDate()); // 👇️ Sun Jan 16 2022 15:26:30 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 would adjust the month and/or year values 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); } // 👇️ Sun Jan 09 2022 15:34:30 console.log(getLastWeeksDate()); // 👇️ Sun Jan 16 2022 15:34:30 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.