To calculate working hours, I need to separately calculate the number of hours that the user worked during working hours(09:00 – 17:00) and outside of working hours (overtime) and return their sum.
For example, the user worked from 2023-01-23 15:00 to 2023-01-23 22:00, which is 2023-01-23 15:00 to 2023-01-23 17:00 in the working hours and 2023-01-23 17:00 to
2023-01-23 22:00 is overtime.
Now, how can I find out how much of the user’s working hours are within the range of 9:00 to 17:00 and how much is outside the hours?
foreach ($timeSheets as $key => $time) {
if ($time->is_in == 1) {
$time_in = new Carbon($time->event_at);
$time_out = new Carbon($timeSheets[$key + 1]->event_at);
[$time_in, $time_out] = $this->getTimeZoneName($bill->BillingRateTimezone->timezone, $time_in, $time_out);
// period of his/her work time
$start_time = $time_in->format("H:i");
$end_time = $time_out->format("H:i");
// How can I calculate how much of user work time is between 9:00-17:00 and how much is outside of this ??
$sumOfInside = "?";
$sumOfOutside = "?";
}
}
2
Answers
You can use https://github.com/kylekatarnls/business-time
For instance with the method diffInBusinessMinutes you get a number of minutes in, and with Carbon diffInMinutes, you get the total, so minutes out are the first subtracted from the total.
There’s probably a better way to go around it but a bunch of conditionals to cover every case could work.
Case 1:
Case 2:
Case 3:
Case 4:
Case 5:
Case 6:
Using
Carbon
‘s diff method can be very helpful for this, but since datetimes are needed,Carbon::today()
(or simplytoday()
if you want to use the laravel helper) can give us a date with it’s time at 00:00:00, which is perfect for our needs. As for getting the sum, we can incrementally add to a couple of instances ofCarbonInterval
.And then you can either print out the interval with the
forHumans()
method or get the total hours and minutes.