Home > Software design >  Javascript - Adding Days to a Loop
Javascript - Adding Days to a Loop

Time:10-04

I have the following

       var my_date = '2021-09-27';
        
        my_date = new Date(my_date);
        var new_date = new Date();
        
        for(var i=0; i<10; i  ) 
        {
        new_date.setDate(my_date.getDate()   i);
        var this_date = new_date.toISOString();
        console.log(this_date);
        }

I was expecting it to output

2021-09-27T19:21:26.361Z
2021-09-28T19:21:26.361Z
2021-09-29T19:21:26.361Z
2021-09-30T19:21:26.361Z
2021-10-01T19:21:26.361Z
2021-10-02T19:21:26.361Z
2021-10-03T19:21:26.361Z
2021-10-04T19:21:26.361Z
2021-10-05T19:21:26.361Z
2021-10-06T19:21:26.361Z

but for some reason it outputs

2021-10-27T19:21:26.361Z
2021-10-28T19:21:26.361Z
2021-10-29T19:21:26.361Z
2021-10-30T19:21:26.361Z
2021-10-31T19:21:26.361Z
2021-11-01T19:21:26.361Z
2021-12-03T19:21:26.361Z
2022-01-03T19:21:26.361Z
2022-02-04T19:21:26.361Z
2022-03-08T19:21:26.361Z

As you can see it starts in October not September, and then when it hits the 31st it starts to jump months.

Why is this script behaving like this?

All the examples I have found online seem to suggest this would work.

Thanks

CodePudding user response:

Because setDate only changes days, so when you create new Date() it has current month in it. You have to copy original date to make this works properly.

Here's the fix:

var my_date = '2021-09-27';
        
my_date = new Date(my_date);

        
for(var i=0; i<10; i  ) 
{
  // clone date
  var new_date = new Date(my_date.getTime())
  new_date.setDate(my_date.getDate()   i);
  var this_date = new_date.toISOString();
  console.log(this_date);
}
  • Related