1

I feel like there is something I'm missing about this, I'm trying to add 7 days to a current date, then 14, then 21. What I'm ending up with is a compounding of intervals rather than current date + 7, then current date + 14 etc.

var date = new Date();

for(var i = 0; i < 4; i++){
                var tempDate = date;
                var repeatson = tempDate.setDate(date.getDate() + (i*7));
                var repeats = new Date(repeatson);
                console.log(repeats);
                }

Results in:

"2015-03-17T21:03:13.326Z"
"2015-03-24T21:03:13.326Z"
"2015-04-07T20:03:13.326Z"
"2015-04-28T20:03:13.326Z"

Rather than the desired, 24th, 31st & 8th

0

1 Answer 1

3

var tempDate = date; simply assigns a reference to date. You are not creating a copy. Similarly, setDate does not return a new date, it mutates the date itself.

One solution would be to create a copy:

var tempDate = new Date(date);

Your loop could be simplified to

var repeats = (new Date(date)).setDate(date.getDate() + (i*7))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.