Get last week's Date using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
2 min

banner

# 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 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, ); } // ๐Ÿ‘‡๏ธ Wed Jul 19 2023 00:00:00 console.log(getLastWeeksDate()); // ๐Ÿ‘‡๏ธ Wed Jul 26 2023 10:46:35 console.log(new Date());

get last week date

The code for this article is available on GitHub

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 will adjust the month and/or year if the days of the month value is negative.

# Get last week's Date preserving the time

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); } // ๐Ÿ‘‡๏ธ Wed Jul 19 2023 10:47:53 console.log(getLastWeeksDate()); // ๐Ÿ‘‡๏ธ Wed Jul 26 2023 10:47:53 console.log(new Date());

get last week date preserving the time

The code for this article is available on GitHub

The getTime() method returns the number of milliseconds since the Unix epoch for the specific Date.

By subtracting a week's 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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev