javascripttimetabletimeslots

How to calculate timeslots between two times for a timetable


I have a starting time and end time at school. and I want to generate a timetable for that school using start time and end time and given timeslot.

Time is 24 hours.

ex:-

const startingTime = {
   startHour: 8,
   startMinutes: 30
}

const endTime = {
   endHour: 17,
   endMinutes: 30
}

And also I can mention a timeslot. there are two timeslot types (1 Hour or 30 Minutes).

when all these parameters set, I need an array with all timeslots between starting time and end time.

I will give a simple example

My school's starting time and end time as follows,

const startingTime = {
   startHour: 8,
   startMinutes: 30
}

const endTime = {
   endHour: 9,
   endMinutes: 30
}

IF timeslot is 1 Hour

what I need from these data is,

8:30 - 9: 30

IF timeslot is 30 Minutes

8:30 - 9:00

9:00 - 9:30

Another example

const startingTime = {
   startHour: 8,
   startMinutes: 30
}

const endTime = {
   endHour: 2,
   endMinutes: 00
}

for this kind of scenario, we cannot use 1 Hour timeslot because there is a additional 30 Minutes . so I have already validated, only we can mention 30 Minutes timeSlot only therefore in this scenario we can use only 30 Minutes time Slot.

IF timeslot is 30 Minutes

8:30 - 9:00

9:00 - 9:30

9:30 - 10:00

10:00 - 10:30

10:30 - 11:00

like this I need an array, so I can print each an every time slot when I generate the timetable.


Solution

  • Think about using a dates and times library like Luxon (https://moment.github.io/luxon/index.html)

    const slot = Duration.fromMillis(1800000) // 30:00 minutes
    
    const period = {
        startTime: DateTime.local(2020, 1, 1, 8, 30),
        endTime: DateTime.local(2020, 1, 1, 10, 0)
    }
    
    var slots = [];
    var slotCount = Math.trunc((period.endTime.toMillis() - period.startTime.toMillis()) / slot.milliseconds);
    for (var i = 0; i < slotCount; i++) {
        slots[i] = {
            startTime: period.startTime.plus(i * slot.milliseconds),
            endTime: period.startTime.plus((i + 1) * slot.milliseconds)
        }
    }
    
    var formattedSlots = slots.map(x => ({
        startHour: x.startTime.hour, 
        startMinutes: x.startTime.minute,
        endHour: x.startTime.plus(slot).hour,
        endMinutes: x.startTime.plus(slot).minute,
    }));
    
    console.log(formattedSlots);
    // Prints out:
    // 0: {startHour: 8, startMinutes: 30, endHour: 9, endMinutes: 0}
    // 1: {startHour: 9, startMinutes: 0, endHour: 9, endMinutes: 30}
    // 2: {startHour: 9, startMinutes: 30, endHour: 10, endMinutes: 0}