0

How do build an array with minute counts per hour within a set date range.

Assuming you have these dates

const start = new Date('2019-04-04 12:14');
const end = new Date('2019-04-04 16:21');

How do you turn that into and array looking like this:

const minutes_per_hour = [
    {
        hour: 12,
        minute_count: 46
    },
    {
        hour: 13,
        minute_count: 60
    },
    {
        hour: 14,
        minute_count: 60
    },
    {
        hour: 15,
        minute_count: 60
    },
    {
        hour: 16,
        minute_count: 21
    }
];
Malibur
  • 1,695
  • 5
  • 22
  • 31

1 Answers1

1

Here's a simple function that should do what you want. It works by repeatedly calculating the minutes until the next hour (or end, if that's closer) and incrementing to the next hour, eventually stopping when end is reached.

/**
 * Gets the minutes in each sequential hour in a time range
 * @param {Date} start
 * @param {Date} end
 * @return {{hour:number, minute_count:number}[]}
 */
function getMinutesPerHour(start, end) {
  const outp = [];
  let current = start;
  while (current < end) {
    const minutesToNextHour = 60 - current.getMinutes();
    const nextHour = new Date(+current + minutesToNextHour * 60 * 1000);
    const minutes = nextHour > end
      ? end.getMinutes() - current.getMinutes()
      : minutesToNextHour;
    outp.push({ hour: current.getHours(), minutes: minutes, });
    current = nextHour;
  }
  return outp;
}

console.log(getMinutesPerHour(new Date('2019-04-04 12:14'), new Date('2019-04-04 16:21')));
Birjolaxew
  • 807
  • 9
  • 25