DEV Community

Cover image for Calculate class start & end time then book class
MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

Calculate class start & end time then book class

I use moment.js for time comparison

My usecase

Class have class availability start & end time

User selected time

 const selectedTime= moment(userSelectedTime)
Enter fullscreen mode Exit fullscreen mode

Given start and end time,class length is a minute of class like 60 equal 1 clock

const startSelectedTimes = moment(availableLength.start)
const endSelectedTimes = moment(availableLength.end).subtract(class.length,'minutes')
Enter fullscreen mode Exit fullscreen mode

1 Check
if user selected time is before start time then it throw a error

 if(startTimes.isBefore(startSelectedTimes)){
     throw error...
     return
}
Enter fullscreen mode Exit fullscreen mode

2 Check
if user selected time is after end time then it throw a error

 if(startTimes.isAfter(endSelectedTimes)){
     throw error...
     return
}
Enter fullscreen mode Exit fullscreen mode

After some booked classes your have array of booked class with start and end time

Booked class start & end time loop throw i is loop variable

const classStartTime = moment(i.start)
const classEndTime = moment(i.end)
const checkBack = moment(i.start).subtract(class.length,"minutes")
const checkNext = moment(i.end).add(class.length,"minutes")
Enter fullscreen mode Exit fullscreen mode

3 Check
if the selected time is between start & end time then throw error

 if (startTimes.isBetween(classStartTime, classEndTime)===true) {
     throw error...
     return ;
 }
Enter fullscreen mode Exit fullscreen mode

4 Check
Subtract class length to start time then check there is a class between selected time then throw error

 if(startTimes.isBetween(checkBack,classStartTime)===true){
      throw error...
      return ;
  }
Enter fullscreen mode Exit fullscreen mode

5 Check
Add class length to end time and then check if there is a class between selected time then throw error

 if(startTimes.isBetween(classEndTime,checkNext)===true){
    throw error..
   return ;
  }
Enter fullscreen mode Exit fullscreen mode

finally
Book class

Your logic here 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)