Search code examples
angulartimepickercalculationperiodtimetable

How do we calculate the period times based on user's input of start-time and end-time for the day in angular?


I'm setting up a timetable project for school management. I wanted to get the start time and end time of the day by a school admin for which I'm using a modal dialog.enter image description here The above image holds only static period times for 9 different periods with equal interval of time. enter image description hereThe above is the modal which i'm using to get the desired times for each factors in the timetable period duration.

Say there are 9 periods in a day, I wanted the time to be broken down into 9 slots based on the user's start and end time of the day and along with the user's period duration.

I haven't tried any code as i didn't get a clear idea of how i'm gonna do that. I have added some screenshots though.

Periods needs to be calculated based on the user's period duration, When 9 periods are allotted for the day, it should automatically be broken down in to 9 different time slots.


Solution

  • Use below given code to divide given time range in 9 equal parts:

        let arr = [];
        let dt1 = new Date().setHours(9, 45, 0); // this would be given by user as input
        let dt2 = new Date().setHours(16, 30, 0);// this would be given by user as input
        const interval = (dt2-dt1)/9;
        for (let i=0; i<9; i++) {
            const period = {
                start: new Date(dt1+(i*interval)),
                end: new Date(dt1+((i+1)*interval))
            }
            arr.push(period);
         }
    

    You can loop through array and get the start end time of each slot:

    arr.forEach((slot, index) => {
        // index 0 will be first slot and last index will be last one
        console.log(`Slot start: ${slot.start}`);
        console.log(`Slot end: ${slot.end}`);
    })