Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda