So I have this table with a start time and an end time and I am calculating hours. This works just fine unless the end time is midnight.
I have TIME fields in my database for start and end.
This is the calculation
@php
$start = \Carbon\Carbon::parse($person->clocked_in_at);
$end = \Carbon\Carbon::parse($person->clocked_out_at);
$diff = $start->diff($end)->format('%H:%I');
@endphp
If the start time is 07:30:00 and the end time is 13:00:00 it properly calculates to 05:30 hours. However if the start time is 23:30:00 and the end time is 00:00:00 which should calculate to 30 minutes, it calculates to 23:30:00
What am I missing here?
CodePudding user response:
you need to add this year-month-day
like this:
$start = \Carbon\Carbon::parse('2015-5-5 23:30:00');
$end = \Carbon\Carbon::parse('2015-5-6 00:00:00');
$diff = $start->diff($end)->format('%H:%I');
note: the day is begining on 00:00:00
hopefully that is help you
CodePudding user response:
If clocked_out is less than the clocked-in then you need to factor in the date change.
@php
$start = \Carbon\Carbon::parse($person->clocked_in_at);
$end = \Carbon\Carbon::parse($person->clocked_out_at);
@php
if($end->lt($start) {
$end->addDay();
}
@endphp
$diff = $start->diff($end)->format('%H:%I');
@endphp
This should also work for other cross-midnight shifts not just those that end exactly at midnight
Blade view is not the place to be doing this calculation though.