technology logo
technology logo

Dividing a date range into equal chunks containing a set number of day chunks in JavaScript.

share link

by Saqib dot icon Updated: Nov 17, 2022

Guide Kit Guide Kit  

function getDateBlocks(start, end, maxDays) {
  let result = [];
  // Copy start so don't affect original
  let s = new Date(start);

  while (s < end) {
    // Create a new date for the block end that is s + maxDays
    let e = new Date(s.getFullYear(), s.getMonth(), s.getDate() + maxDays);
    // Push into an array. If block end is beyond end date, use a copy of end date
    result.push({start:new Date(s), end: e <= end? e : new Date(end)});
    // Increment s to the start of the next block which is one day after 
    // the current block end
    s.setDate(s.getDate() + maxDays + 1);
  }
  return result;
}

console.log(getDateBlocks(new Date(2021,0,1), new Date(2021,0,20), 6));