How to get the dates for the past 7 days in JavaScript

1 Answer

0 votes
const past7DaysDates = [...Array(7).keys()].map(index => {
  	const date = new Date();
  
  	date.setDate(date.getDate() - index - 1);

  	return date;
});

const dates = past7DaysDates;
 
for (let i = 0; i < dates.length; i++) {
    console.log(dates[i].toDateString());
}

 
 
 
 
/*
run:
 
"Thu Mar 31 2022"
"Wed Mar 30 2022"
"Tue Mar 29 2022"
"Mon Mar 28 2022"
"Sun Mar 27 2022"
"Sat Mar 26 2022"
"Fri Mar 25 2022"
 
*/

 



answered Apr 1, 2022 by avibootz
edited Apr 1, 2022 by avibootz
...