I have a function that when called, it will add 7 days to the inputted date. The format for the date is YYYY-MM-DD (i.e. 2022-03-02)
for(let i = 0; i < repeatCount; i )
{
date = addWeek(date);
}
function addWeek(date)
{
let temp = new Date(date);
//console.log("Old Date: ");
//console.log(temp.toISOString().split('T')[0])
//console.log(temp.getDate());
temp.setDate(temp.getDate() 7);
console.log("New Date: ");
console.log(temp.toISOString().split('T')[0])
//console.log("returning date");
return temp.toISOString().split('T')[0];
}
For some reason, when the function is called as part of a repeat (React Web Application that involves recurring events), the addWeek function will not increment correctly a single time but then increment correctly the rest of the time.
Here's the input from my most recent log when I set repeatCount to 5:
Old Date:
2022-03-04
New Date:
2022-03-11
Old Date:
2022-03-11
New Date:
2022-03-17
Old Date:
2022-03-17
New Date:
2022-03-24
Old Date:
2022-03-24
New Date:
2022-03-31
Old Date:
2022-03-31
New Date:
2022-04-07
As you've probably noticed, it increments the week correctly with the exception of the second repeat. I've tested this multiple times with different dates, and each time, it is only the second iteration that is incremented incorrectly. Everything else works fine.
Please help. I'm losing my mind over this.
I forgot to add earlier: addWeek takes the date as a string input.
CodePudding user response:
https://jsfiddle.net/4wm1vz9d/1/
function addWeek(date)
{
date.setDate(date.getDate() 7)
}
let date = new Date();
console.log(date)
for(let i = 0; i < 5; i )
{
addWeek(date)
console.log(date)
}
CodePudding user response:
seems like you have a common error: Calling your variables the same globally and inside a function.
I tried the code myself and got the expected result. Try renaming your functions parameter and it should work. You are probably adding 1 to the global date variable at some point which messes up the function aswell.