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

232
Vistas
How to create date intervals in javascript

I need to call an api, passing start and end date, but given that the interval is too wide I am thinking that I need to do several calls using smaller date intervals. This is how I am trying to set start and stop dates:

const daysBracket = 15;
let fromDate = new Date('2020-04-01');
let toDate = new Date('2020-06-01');
let stopDate = new Date('2020-04-01');

while(fromDate <= toDate) {
  stopDate.setDate(fromDate.getDate() + (daysBracket - 1));
  console.log('Start: ' + fromDate.toDateString());
  console.log('Stop: ' + stopDate.toDateString());
  console.log('- - - - - - - - - - - - -');

  fromDate.setDate(fromDate.getDate() + daysBracket);
}

but I am getting this result (start date is updated correctly but stop date doesn't change accordingly):

Start: Wed Apr 01 2020
Stop: Wed Apr 15 2020
- - - - - - - - - - - - -
Start: Thu Apr 16 2020
Stop: Thu Apr 30 2020
- - - - - - - - - - - - -
Start: Fri May 01 2020
Stop: Wed Apr 15 2020
- - - - - - - - - - - - -
Start: Sat May 16 2020
Stop: Thu Apr 30 2020
- - - - - - - - - - - - -
Start: Sun May 31 2020
Stop: Fri May 15 2020
- - - - - - - - - - - - -
Start: Mon Jun 15 2020
Stop: Fri May 29 2020
- - - - - - - - - - - - -
Start: Tue Jun 30 2020
Stop: Sat Jun 13 2020
- - - - - - - - - - - - -

Can you please tell me what I am doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I geuss this answer provides some clarity. The following works:

const daysBracket = 15;


let fromDate = new Date('2020-04-01');
let toDate = new Date('2020-06-01');
let stopDate = new Date('2020-04-01');
    
function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

while(fromDate <= toDate) {
  stopDate = addDays(fromDate, daysBracket -1)  
  console.log('Start: ' + fromDate.toDateString());
  console.log('Stop: ' + stopDate.toDateString());
  console.log('- - - - - - - - - - - - -');
fromDate = addDays(fromDate, daysBracket);
}

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