Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda