javascriptdatedate-manipulation

Adding dates in javascript with unexpected results


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());
}

Solution

  • You are currently just always adding 7 days to the start date, what you should do in order to produce the wanted result is:

    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);
     start.setDate(nextDay.getDate());
     console.log("The next day is:"+nextDay.toUTCString());
    }

    Also increment the start every time, or else you are just going to always add 7 days to the start, which is always the same date.

    I realize this isn't the best way of coding this, you don't need the nextDay variable:

    var start = new Date('2018-01-01');
    
    for (day = 1; day <= 5; day++) 
    {
     console.log("Start day "+start.toUTCString());
     start.setDate(start.getDate()+7);
     console.log("The next day is:"+start.toUTCString());
    }