'How to calculate the total hours (working hours) after subtracting from a set of time ranges (break)
I have a form to apply a leave, where you have the option to mention the start date and time, end date and time of the leave applied. I need to find the total duration in hours and minutes which I have already implemented. But there are 2 factors that needs to considered here.
The applied leave should reside within the company working hours. Example if the user applies leave on
3rd Feb 2022 08:00 AMto3rd Feb 09:00 PM, and if the company working hours is09:00 AM to 06:00 PM, the leave duration should be taken from3rd Feb 2022 09:00 AM to 3rd Feb 06:00 PMThere could be multiple breaks between a day, say a lunch break from
01:00 PM to 02:00 PM, also a break from04:00 PM to 04:30PM. So this duration should also be deducted from the applied leave if the breaks resides between the applied leave range.
I know this could be done by looping through each time range and checking if it resides between the breaks. But I'm wondering if there is a better/more elegant way to approach this situation. Any help would be appreciated.
Solution 1:[1]
Instead of thinking of breaks in a day, think of it like blocks of work hours. For example, Feb 3rd, 9am to 1pm, Feb 3rd, 2pm to 4pm, Feb 3rd, 4pm to 6pm, Feb 4th, 8am to 11am. Store your data in this form and you do not need to calculate breaks, but you may need to take 2 partial work blocks from the beginning and end of the leave.
So you would have some sort of object with all the working hours in chronological order, probably indexed by year and day, with each day having an array of work blocks. You find where your start time and end time land in the arrays of corresponding days, and possibly calculate partial work blocks. Then you sum all of the work blocks in between.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
