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.
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()))
Try this
var endDate = new Date(2024,8,13);
var startDate = new Date(2021,8,13);
var currentDate = startDate;
while(currentDate < endDate)
{
document.getElementById("dateList").innerText += currentDate + "\n";
currentDate.setDate(currentDate.getDate() + 7);
}
<div id="dateList"></div>