Home > Software engineering >  How to get the ALL the dates of the current week?
How to get the ALL the dates of the current week?

Time:11-23

Is there a way to get all the dates of the current week? For example today is 11/22/2021. So I need an array of ["11/21/2021", "11/22/20201", "11/23/2021", "11/24/2021", "11/25/2021", "11/26/2021", "11/27/2021"]

Also this array needs to be consistent for the entire week until it is Sunday, then it will create a new array.

CodePudding user response:

Something like that ?

Array.from(Array(7).keys()).map((idx) => {const d = new Date(); d.setDate(d.getDate() - d.getDay()   idx); return d; });

Some explanation, Array(7) will create an empty array with 7 entries.

Array(7).keys() will return an iterator with the array keys.

Array.from(Array(7).keys()) will transform the iterator into a new array with 7 entries containing integers (aka [0, 1, 2, 3, 4, 5, 6])

d.getDate() - d.getDay() idx, we take the current day (23), remove the day of week (0 for Sunday, 2 for Tuesday... Basically we calculate the last Sunday date) et add number of days to have every date in the week.

  • Related