Skip to content Skip to sidebar Skip to footer

Dividing A Date Range Into Equal Chunks Containing A Set Number Of Day Chunks In Javascript?

I am trying to write a function but I'm drawing a blank trying to wrap my head around how to achieve my goal. I am writing a wrapper for an API that filters data by a start date an

Solution 1:

Start with the start date and add maxDays to get the end of the block. If the block date is greater than the end date, use the end date instead. Then add maxDays to the start and go again until the start is >= than the end.

Copy dates before pushing into the array so don't affect original or ongoing processing.

functiongetDateBlocks(start, end, maxDays) {
  let result = [];
  // Copy start so don't affect originallet s = newDate(start);

  while (s < end) {
    // Create a new date for the block end that is s + maxDayslet e = newDate(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:newDate(s), end: e <= end? e : newDate(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(newDate(2021,0,1), newDate(2021,0,20), 6));

You need to work out if the dates are inclusive or not. In the above, 6 day blocks will go 1–7 Jan, 8–14 Jan, etc. If you want 1–6, 7–13, etc. subtract 1 from maxDays before doing the while loop.

You should also check that maxDays is a positive integer or the loop may be be infinite…

Solution 2:

Just keep adding days using Date.prototype.setDate() until you're past the end date:

constchunk = (start, end, days) => {
  const result = [];
  const current = newDate(start.getTime());
 
  do {
    const d1 = newDate(current.getTime());
    const d2 = newDate(current.setDate(current.getDate() + days));
    
    result.push({
      start: d1,
      end: d2 <= end ? newDate(d2.setDate(d2.getDate() - 1)) : end
    });
  } while (current <= end);
  
  return result;
};

const chunks = chunk(
  newDate(Date.UTC(2021, 0, 1)),   // Jan 1, 2021newDate(Date.UTC(2021, 11, 31)), // Dec 31, 202190// 90 days
);

console.log(chunks);

These types of methods are usually annoying to write in JavaScript due to the fact that Date objects are mutable and the date/time API is quite poor. I mostly work around that by only mutating the Date object named current as I progress through the date intervals.

Post a Comment for "Dividing A Date Range Into Equal Chunks Containing A Set Number Of Day Chunks In Javascript?"