Skip to content

Instantly share code, notes, and snippets.

@celorodovalho
Last active November 29, 2020 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celorodovalho/9227d11b2ad3bcfc7709e4088398efec to your computer and use it in GitHub Desktop.
Save celorodovalho/9227d11b2ad3bcfc7709e4088398efec to your computer and use it in GitHub Desktop.
Sum Array of Hours, Minutes, Seconds with PHP Carbon
function sumTime($entitiy)
{
$time = (array)$entitiy;
$time = array_filter($time, function ($item) {
return !in_array($item, ['00:00:00', '0:00:00']);
});
$begin = Carbon::createFromFormat('H:i:s', '00:00:00');
$end = clone $begin;
foreach ($time as $element) {
$dateTime = Carbon::createFromFormat('H:i:s', $element);
$end->addHours($dateTime->format('H'))
->addMinutes($dateTime->format('i'))
->addSeconds($dateTime->format('s'));
}
return sprintf(
'%s:%s:%s',
$end->diffInHours($begin),
$end->format('i'),
$end->format('s')
);
}
@celorodovalho
Copy link
Author

Test:

echo sumTime(['7:50:10', '0:00:00', '0:25:25']);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment