0

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?

user3174311
  • 1,714
  • 5
  • 28
  • 66
  • Perhaps a combination of [this](https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates) and [that](https://stackabuse.com/how-to-split-an-array-into-even-chunks-in-javascript/) – Yarin_007 Jun 10 '22 at 13:17

1 Answers1

1

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);
}
Robert-Jan Kuyper
  • 2,418
  • 12
  • 22
  • Thanks @Robert, I don't get why it is missing a day for every loop though. Still start date is correct but stop date is wrong. – user3174311 Jun 10 '22 at 13:35
  • 1
    I get it. if you change **stopDate = addDays(stopDate, daysBracket -1)** to **stopDate = addDays(fromDate, daysBracket -1)** I will approve your answer. Thank you. – user3174311 Jun 10 '22 at 13:41