Get last week's Date using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get last week's Date using JavaScript #

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.

index.js
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.

The Date() object in JavaScript automatically rolls over or back and would 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.

index.js
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.

By subtracting a week worth of milliseconds from the value, we get last week's date and preserve the time components.

You can also take a Date object as a parameter in the function to get the date of the previous week for any Date.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.