Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading