Get the Dates for the Past 7 Days using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 18 20222 min read

Get the Dates for the Past 7 Days using JavaScript #

To get the dates for the past 7 days:

  1. Create an array of 7 elements.
  2. Use the map() method to iterate over the array.
  3. On each iteration, create a date object setting the day of the month to the current day of the month minus the index.
index.js
// ✅ start from today's date const past7Days = [...Array(7).keys()].map(index => { const date = new Date(); date.setDate(date.getDate() - index); return date; }); console.log(past7Days); // 👇️ [0, 1, 2, 3, 4, 5, 6] console.log([...Array(7).keys()]);

The code snippet above includes today's date in the results array.

If you want to start at yesterday's date, use this code snippet instead.

index.js
// ✅ start from yesterday's date const past7Days = [...Array(7).keys()].map(index => { const date = new Date(); date.setDate(date.getDate() - (index + 1)); return date; }); console.log(past7Days);

We created an array of 7 elements that stores indexes starting at 0.

index.js
// 👇️ [0, 1, 2, 3, 4, 5, 6] console.log([...Array(7).keys()]);

The function we passed to the Array.map method gets called with each element in the array.

On each iteration, we used the Date() constructor to create a new Date object.

The setDate method changes the day of the month for the given Date object.

To get the previous 7 days we subtracted the index from the current day of the month.

The getDate method returns an integer between 1 and 31 that represents the day of the month for the given date.

If you want to start including dates from yesterday onwards, you just have to add 1 to the index, otherwise the first element in the array will be today's date.
Use the search field on my Home Page to filter through my more than 1,000 articles.