Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Javascript - Adding Days to a Loop

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!