Skip to content
Advertisement

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?

Advertisement

Answer

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);
}
Advertisement