Search code examples
javascriptnode.jsexpresslogicmomentjs

how to subtract specific part of time javascript momentjs


I want to subtract a specific part of the time. I have timeSlot subtract by bookedSlot and duration and then return break slot array.

const timeSlots [{from: '10:00 am', to: '01:00 pm'}];
const bookedSlot = "12:00 pm"
const duration = "30min"

result need

const res = [
 {from: '10:00 am', to: '12:00 pm'},
 {from: '12:30 am', to: '01:00 pm'}
]

Solution

  • If I got your question correctly, this is some basic code you might consider as a solution for your problem. That's pretty rough solution, you might simplify it if you prefer.

    function getFreeSlots(startInterval, endInterval, slotStartTime, slotDurationMin){
      var startTime = moment(startInterval, 'HH:mm');
      var endTime = moment(endInterval, 'HH:mm');
      var slotTime = moment(slotStartTime, 'HH:mm');
      var timeSlots = [];
    
      // we are going to add 1 day in case startTime > endTime 
      if(endTime.isBefore(startTime))
        endTime.add(1, 'day');
    
      // split interval into slots
      // first slot
      timeSlots.push({
        "from": startTime.format('HH:mm'),
        "to": slotTime.format('HH:mm')
      });
      
      var slotEndTime = slotTime.add(slotDurationMin, "minutes")
      // second slot
      timeSlots.push({
        "from": slotEndTime.format('HH:mm'),
        "to": endTime.format('HH:mm')
      });
      return timeSlots;
    }
    
    var res = getFreeSlots("10:00 am", "13:00 pm", "12:00 pm", 30);
    console.log(res);
    

    You might need to just add some transformer for

    const duration = "30min"
    

    so, you can pass some definite interval to the function.