I’m trying to pass in a startdate and enddate in the format of YYYY-MM-DD
and then have a const
return an array whose items represent a date range. Here is the code I have right now that ALMOST works, however there’s a weird bug I’ll mention in a moment.
Code:
const getWeeksInRange = (startDate, endDate) => {
const weeks = [];
// Copy the start date
let currentDate = new Date(startDate);
let futureDate = new Date(endDate);
// Iterate over the range of dates
while (currentDate <= futureDate) {
const firstDate = new Date(currentDate); // Copy the current date
const lastDate = new Date(currentDate); // Copy the current date
lastDate.setDate(lastDate.getDate() + 6); // Move to the last day of the week
weeks.push(`${firstDate.toISOString().slice(0, 10)} to ${lastDate.toISOString().slice(0, 10)}`);
currentDate.setDate(currentDate.getDate() + 7); // Move to the next week
}
return weeks;
}
An example call would be const resultArray = getWeeksInRange('2024-04-02', '2024-04-30')
This exact call returns:
[ "2024-04-29 to 2024-05-05","2024-04-22 to 2024-04-28", "2024-04-15 to 2024-04-21", "2024-04-08 to 2024-04-14", "2024-04-01 to 2024-05-08", "2024-04-01 to 2024-04-07"]
I am absolutely bashing my brain out trying to see why "2024-04-01 to 2024-05-08"
could ever be returned and, when I try and pass in a complete date and time like 2024-04-02T17:12:34.326724+00:00
it does the same thing.
Any information would be greatly appreciated!