I need a code that calculates the following for me.
Night shift: 22:00:00 – 06:00:00
An employee works from 04:30:00 to 12:00:00. Here the output should be 1.50.
Another employee works from 21:00:00 to 08:00:00. Here the output should be 8.00.
Another employee works from 21:00:00 to 03:30:00. Here the output should be 5.50.
I need the number of hours where the night shift overlaps with the working time.
I’ve also tried ChatGPT, but I can’t get it to work.
How many hours are between 2 periods of time, that overlap?
Do you have an example code in PHP for me?
$check_in = $last_stemp->time; //21:00:00
$check_out = $_POST['time']; //07:00:00
$bonusFrom = '22:00:00';
$bonusTo = '06:00:00';
if(strtotime($bonusTo) >= strtotime($check_in)){
$bonus = abs((strtotime($bonusTo) - strtotime($check_in)) / 3600);
}
if(strtotime($check_out) >= strtotime($bonusFrom)){
$bonus = abs((strtotime($check_out) - strtotime($bonusFrom)) / 3600);
}
2
Answers
You could try with:
Output:
It depends.
Does the 2100-0800 shift happen to cross a daylight savings boundary? Because then it can be any one of 10, 11, or 12 hours. Eg:
Output:
Something like this is what you’d want to use if need perfect coverage, your employees are willing to work +/- an hour on daylight savings changes, and you want to track hours/pay them correctly.
If you want to make sure that the shift is always a 11 hours no matter what, then:
Output:
Generally it’s helpful to think of "9 o’clock" without a corresponding date to be largely meaningless information. There are so many edge cases and pitfalls to dealing with dates and times that there are robust libraries like PHP’s DateTime to account for them.