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

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

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 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