Home > Software design >  Find interval between two hours
Find interval between two hours

Time:12-21

I want to caluculate amout time slots avalible based on these inputs:

    let start = req.body.start; //Start of hour
    let end = req.body.end; // End of hour
    let interval = req.body.interval // Interval that the timeslots are going to be set

So with the input of this:

start = 11:00
end = 19:00
interval = 30 //minutes
dif = end - start // as int not time

I want the output to be:

[11:00, 11:30, 12:00, 12:30, 13:00, 
 13:30, 14:00, 14:30, 15:00, 15:30,
 16:00, 16:30, 17:00, 17:30, 18:00, 
 18:30, 19:00]

in string format of course

found a semi working suliton with the interval of 20 minutes:


    for (let i = 0; i < dif; i  ) {
      let hourArray = [];
      let hour = parseInt(start)   i;
      for (let j = 0; j < 60 / interval; j  ) {
        let hourTime = `${hour}:${interval * j}`;
        if (j === 0) {
          hourTime = `${hour}:00`;
        }
        hourArray.push(hourTime);
      }
      console.log(hourArray);
    }

CodePudding user response:

We can start by converting hh:mm timeslots to minutes from midnight, we then get the start time and endtime in minutes - startMins and endMins

We'll then use a for loop to create each timeslot, adding interval minutes for each iteration.

Finally we'll output by converting each timeslot to hh:mm format.

function hhMMToMinutes(hhmm) {
    const [hours, mins] = hhmm.split(':').map(Number);
    return hours * 60   mins;
}

function minutesToHHMM(minutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return (hours   '').padStart(2, '0')   ':'   (mins   '').padStart(2, '0')
}

function getTimeSlots(start, end, interval) {
    const startMins = hhMMToMinutes(start);
    const endMins = hhMMToMinutes(end);
    const result = [];
    for (let mins = startMins; mins <= endMins; mins  = interval) {
        result.push(minutesToHHMM(mins))
    }
    return result;
}

console.log('Timeslots:', getTimeSlots('11:00', '19:00', 30))
.as-console-wrapper { max-height: 100% !important; }

  • Related