I am trying to loop over and add 7 days to the date, and I am not sure where I am going wrong. The dates get crazy after the first iteration of the loop.
What I am trying to achieve is Jan 1 next day is jan 8 then jan 8 and jan 15 etc. Its incrementing by a month instead of the 8 days.
Printing
start day Mon, 01 Jan 2018 00:00:00 GMT
The next day is: Mon, 08 Jan 2018 00:00:00 GMT
start day Mon, 08 Jan 2018 00:00:00 GMT
The next day is:Thu, 08 Feb 2018 00:00:00 GMT
var start = new Date('2018-01-01');
var nextDay = new Date(start);
for (day = 1; day <= 5; day++)
{
console.log("start day "+nextDay.toUTCString());
nextDay.setDate(start.getDate()+7);
console.log("The next day is:"+nextDay.toUTCString());
}
nextDay.setDate(start.getDate()+7);should probably benextDay.setDate(nextDay.getDate()+7);getDate()gets the day of the current month in your local timezone. Yourstartdate is actually the last day of the previous year, December 31 (output its value, but not in UTC!). So each iteration, you're setting the date to 38 days, which isn't valid, so the date object increments the month. You can avoid this situation by usinggetUTCDateinstead.