Search code examples
javascriptangularmomentjsmoment-timezone

Generating 30 minutes time slots going into next day using moment.js


var x = {
    next-slot: 30,
    start-time: '21:00',
    end-time: '05:00'
}

I want to generate time slots , starting from start Time till end Time. Output should be

[21:00, 21:30, 22:00, 22:30, 23:00, 23:30, 00:00, 00:30, 01:00, 01:30, 02:00, 02:30, 03:00, 03:30, 04:00, 04:30]

I am doing below logic Its working for (Below Date range) start-time: '05:00', end-time: '21:00' Not Working For : (Below Date range) start-time: '21:00', end-time: '05:00'

const hours = [];
          for (
            let hour = Number(start-time[0]);
            hour <= Number(end-time[0]);
            hour++
          ) {
              hours.push(moment({ hour }).format('kk:mm'));
              hours.push(
                moment({
                  hour,
                  minute: 30,
                }).format('kk:mm')
              );
          }

Solution

  • This is what you need. To get the time you will use format as HH:mm for start time in data.

    The end time you have is in the next day so we need to use moment.js add() function which we will use to add 1 day to end time.

    Next while loping over the time we will set interval from our data which is set to 30 in moment.js minutes

    Run snippet below to see it working.

    //Data
    let x = {
      slotInterval: 30,
      openTime: '21:00',
      closeTime: '05:00'
    };
    
    //Format the time
    let startTime = moment(x.openTime, "HH:mm");
    
    //Format the end time and the next day to it 
    let endTime = moment(x.closeTime, "HH:mm").add(1, 'days');
    
    //Times
    let allTimes = [];
    
    //Loop over the times - only pushes time with 30 minutes interval
    while (startTime < endTime) {
      //Push times
      allTimes.push(startTime.format("HH:mm")); 
      //Add interval of 30 minutes
      startTime.add(x.slotInterval, 'minutes');
    }
    
    console.log(allTimes);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>