How To Create Time Slots in Javascript/ React/ Angular ?

time-slot-generator


Many time situation comes when as a part of your project you are required to create time slots. This can come when you are developing an application in which booking is there of some kind or other. Booking can be for doctor appointments, meetings, time table of school, etc.

After going to this blog, you will get to know how easy it is to create time slots in javascript/ react/ angular/ vue.js. You can use the logic of creating time slots in your preferred language like python, c#, swift.


Problem -

You are required to create time slots during the time duration [ 8 AM - 1 PM] and [4 PM - 8 PM].
Each slot should be of 1 hour 5 minutes and there should be 10 minutes gap in between each slot. slotConfig object holds the configuration values to be used to create slots.


var slotConfig = {
    "configSlotHours":"01",
    "configSlotMinutes":"5",
    "configSlotPreparation":"10",
    "timeArr": [
       {"startTime":"08:00", "endTime":"13:00"},
       {"startTime":"16:00", "endTime":"20:00"}
    ]
}


According to the above slotConfig JSON -   -> configSlotHours - Hours in each slot.
   -> configSlotMinutes - Minutes in each slot.

   -> configSlotPreparation - Duration in between slots.
   -> timeArr - Time Duration between which you want to create slots.

Now, that we now know the problem let's create slots the Javascript way -



function createSlots(slotConfig){

     // Getting values from slotConfig using destructuring
    const {configSlotHours,configSlotMinutes,configSlotPreparation,timeArr} = slotConfig;

    // This is the default date that we are using to make use of javascript date functions
    // slotsArray will hold final slots
    // _timeArrStartTime is used to store start time date object from the timeArr
    // _timeArrEndTime is used to store end time date object from the timeArr
    // _tempSlotStartTime is used to create slots by adding config values and check that the time is less than the end time and lies withing the duration specified
    // _startSlot holds value of start date time of slot
    // _endSlot holds value of end date time of slot


    let defaultDate = new Date().toISOString().substring(0,10)
    let slotsArray = []
    let _timeArrStartTime;
    let _timeArrEndTime;
    let _tempSlotStartTime;
    let _endSlot;
    let _startSlot;

    // Loop over timeArr
    for (var i = 0; i < timeArr.length; i++) {

       // Creating time stamp using time from timeArr and default date
       _timeArrStartTime = (new Date(defaultDate + " " + timeArr[i].startTime )).getTime();
       _timeArrEndTime = (new Date(defaultDate + " " + timeArr[i].endTime)).getTime();
       _tempSlotStartTime = _timeArrStartTime;

       // Loop around till _tempSlotStartTime is less end time from timeArr
       while ((new Date(_tempSlotStartTime)).getTime() < (new Date(_timeArrEndTime)).getTime()) {

         _endSlot = new Date(_tempSlotStartTime);
         _startSlot = new Date(_tempSlotStartTime);

         //Adding minutes and hours from config to create slot and overiding the value of _tempSlotStartTime
         _tempSlotStartTime = _endSlot.setHours(parseInt(_endSlot.getHours()) + parseInt(configSlotHours));
         _tempSlotStartTime = _endSlot.setMinutes(parseInt(_endSlot.getMinutes()) + parseInt(configSlotMinutes));

         // Check _tempSlotStartTime is less than end time after adding minutes and hours, if true push into slotsArr
         if (((new Date(_tempSlotStartTime)).getTime() <= (new Date(_timeArrEndTime)).getTime())) {

           // DateTime object is converted to time with the help of javascript functions
           // If you want 24 hour format you can pass hour12 false

           slotsArray.push({
             "timeSlotStart": new Date(_startSlot).toLocaleTimeString('en-US', {
               hour: 'numeric',
               minute: 'numeric',
               hour12: true
             }),
             "timeSlotEnd": _endSlot.toLocaleTimeString('en-US', {
               hour: 'numeric',
               minute: 'numeric',
               hour12: true
             })
          });
   }

         //preparation time is added in last to maintain the break period
         _tempSlotStartTime = _endSlot.setMinutes(_endSlot.getMinutes() + parseInt(configSlotPreparation));
       }
    }

  return slotsArray;
}


Output




As you can see from the above solution, you can create time slots in javascript on the fly very easily.
Further modification can also be done to this solution, like if you want the slots in 24 hour format or 12 hour format. You can also convert the time according to the locale as well.

If you want you can make the slot config dynamic for different days and create the slots accordingly as well. This is the basic solution which can be used in many ways as per the need of the client. 


For getting a better understanding of date functions check our other tutorial on Javascript Dates -
https://www.geekstutorialpoint.com/2020/05/playing-with-javascript-date-object.html



Thanks for reading, please feel free to contact. 

Post a Comment

0 Comments