Add weekly dates between years

I have a requirement to get all the weekly dates between two years like

Today date is - 13th Sep 2021
After 3 years - 13th Sep 2024

So I need a collection of all the weekly dates between these two dates.

this.allSelectedRegions.push(date as any);

So how to achieve it.

Answer

We can use a while loop to keep adding dates until we reach the required end date. To add 7 days to a date we’ll use Date.getDate() and Date.setDate(). This should also handle DST transitions.

const startDate = new Date(2021, 8, 13);
const endDate = new Date(2024, 8, 13);

let date = startDate;
let result = [];
while (date <= endDate) {
    result.push(date);
    date = new Date(date);
    date.setDate(date.getDate() + 7);
}

console.log('Results:', result.map(d => d.toDateString()))