2

I've seen Split date range into date range chunks and Split date range into several specific date range chunks, that is not what I'm looking for.

I'm looking for simple function from momenjs, that will help me with known start date, end date and number of chunks (slices) to return an array of equal chunks.

07-15-20 start date 07-27-20 end date I want to split it into 12 chunks

result = [07.15.20 00:00, 07.16.20 00:00, 07.17.20 00:00...]

Trouble starts when date is not so straightforward.

For ex. if I have start date as

    minTimeX = moment(sortedTests[0].date).format('x');
    maxTimeX = moment(sortedTests.length - 1].date).format('x');

and I want to divide this into equal 12 chunks and I cannot figure how I can calculate it manually. Is it implemented in momentjs?

deathfry
  • 626
  • 1
  • 7
  • 28

2 Answers2

5

not sure if moment supports what you're looking for, but you can do it in javascript like this

function splitDateIntoEqualIntervals(startDate, endData, numberOfIntervals){

 let diff =  endData.getTime() - startDate.getTime();
 let intervalLength = diff/numberOfIntervals;
 let intervals = [];
 for(let i = 1 ; i <= numberOfIntervals;i++)
   intervals.push(new Date(startDate.getTime()+i*intervalLength))
 return intervals;

}
Ibrahim Rahhal
  • 323
  • 2
  • 9
4

If you need chunks you probably need start, end and maybe avg of these chunks. So you can use this function similar to these proposed by @ibrachim

const splitDateIntoEqualIntervals = (startDate: Date, endDate: Date, numberOfIntervals: number):{start: Date, end: Date, avg: Date}[] => {
  const intervalLength = (endDate.getTime() - startDate.getTime()) / numberOfIntervals
  return [...(new Array(numberOfIntervals))]
    .map((e, i) => {
      return {
        start: new Date(startDate.getTime() + i * intervalLength),
        avg: new Date(startDate.getTime() + (i + 0.5) * intervalLength),
        end: new Date(startDate.getTime() + (i + 1) * intervalLength)
      }
    })
}

It returns array with chunks without arbitral of choice of start or end.

enter image description here

omeralper
  • 9,804
  • 2
  • 19
  • 27
Daniel
  • 7,684
  • 7
  • 52
  • 76