user3242509 user3242509 - 28 days ago 17
Javascript Question

javascript array date error

I am a bit confused about this one.

This piece of code works well but has strange behavior.

var tmpcurdte = eval(dataSource[i].startDate);
tmpcurdte.setDate(tmpcurdte.getDate() + 1);

while (tmpcurdte < tmpenddte) {
console.log("block date: " + tmpcurdte);
blockdayarray[blockdayarray.length] = tmpcurdte;
console.log("blockdayarray: " + blockdayarray);
tmpcurdte.setDate(tmpcurdte.getDate() + 1);
}


Output

block date :Sat Nov 12 2016 00:00:00 GMT+0100 (CET)
blockdayarray :**Sat Nov 12** 2016 00:00:00 GMT+0100 (CET)
block date :Sat Dec 31 2016 00:00:00 GMT+0100 (CET)
blockdayarray :**Sun Nov 13** 2016 00:00:00 GMT+0100 (CET),**Sat Dec 31** 2016 00:00:00 GMT+0100 (CET)
block date :Sun Jan 01 2017 00:00:00 GMT+0100 (CET)
blockdayarray :Sun Nov 13 2016 00:00:00 GMT+0100 (CET),**Sun Jan 01 2017** 00:00:00 GMT+0100 (CET),**Sun Jan 01 2017** 00:00:00 GMT+0100 (CET)
block date :Sat Feb 04 2017 00:00:00 GMT+0100 (CET)
blockdayarray :Sun Nov 13 2016 00:00:00 GMT+0100 (CET),Mon Jan 02 2017 00:00:00 GMT+0100 (CET),**Mon Jan 02 2017** 00:00:00 GMT+0100 (CET),Sat Feb 04 2017 00:00:00 GMT+0100 (CET)


As you can see the previous date in the array changes when I push a new one. Can anyone help/explain this?

Answer

It's because you're pushing the same Date object onto the array repeatedly, and changing its state.

Instead, you want to create a new Date object for the next day:

var tmpcurdte = eval(dataSource[i].startDate);
tmpcurdte.setDate(tmpcurdte.getDate()+1);

while (tmpcurdte < tmpenddte) {
    console.log("block date :" + tmpcurdte);
    blockdayarray[blockdayarray.length]=tmpcurdte;
    console.log("blockdayarray :" + blockdayarray);
    tmpcurdte = new Date(tmpcurdte.getTime());     // ***
    tmpcurdte.setDate(tmpcurdte.getDate() + 1);
}

Side note: I'm not quite sure what you're doing with that call to eval, but there's almost certainly a better way to do whatever it is you have that doing.