I'm having a problem adding two(2) timestamp for example:
00:30:00
00:45:31
========
01:15:31
I can't figure it out how to do it using laravel with carbon...
I'm having a problem adding two(2) timestamp for example:
00:30:00
00:45:31
========
01:15:31
I can't figure it out how to do it using laravel with carbon...
You can't add time like they are integer. One of the way is to convert it to another format and then add it. After adding them, convert it back to time type.
For example, try this:
$time1 = "00:30:00";
$time2 = "00:45:31";
$secs = strtotime($time2) - strtotime("00:00:00");
$result = date("H:i:s", strtotime($time1) + $secs);
dd($result); // "01:15:31"
My practice is to make TimeHelper class where I declare all my static methods that are related with calculations of time. So basically I would make static function like this in TimeHelper class:
public static function addTwoTimes($time1 = "00:00:00", $time2 = "00:00:00"){
$time2_arr = [];
$time1 = $time1;
$time2_arr = explode(":", $time2);
//Hour
if(isset($time2_arr[0]) && $time2_arr[0] != ""){
$time1 = $time1." +".$time2_arr[0]." hours";
$time1 = date("H:i:s", strtotime($time1));
}
//Minutes
if(isset($time2_arr[1]) && $time2_arr[1] != ""){
$time1 = $time1." +".$time2_arr[1]." minutes";
$time1 = date("H:i:s", strtotime($time1));
}
//Seconds
if(isset($time2_arr[2]) && $time2_arr[2] != ""){
$time1 = $time1." +".$time2_arr[2]." seconds";
$time1 = date("H:i:s", strtotime($time1));
}
return date("H:i:s", strtotime($time1));
}
So wherever you need to sum two times just call TimeHelper::addTwoTimes(arg1, arg2);
I took example function from user Cha from this topic: PHP add up two time variables
This how you can achieve adding two times with a Carbon date. The explanation is shown in inline comments
$time1 = '00:30:00';
$time2 = '00:45:31';
// Use the first time to crate a new Carbon date
$baseDate = Carbon::parse($time1);
// Deconstruct the second time into hours, minutes and seconds
list($addHour, $addMinutes, $addSeconds) = explode(':', $time2);
// Add the hours, minutes and seconds to the Carbon object
$baseDate->addHours($addHour)->addMinutes($addMinutes)->addSeconds($addSeconds);
// Print the result: 00:30:00 + 00:45:31 = 01:15:31
echo "{$time1} + {$time2} = " . $baseDate->toTimeString();
You can use CarbonInterval
class from Carbon library:
$durations = [
'00:30:00',
'00:45:31',
];
function getDuration($string)
{
[$hours, $minutes, $seconds] = explode(':', $string);
return CarbonInterval::hours($hours)->minutes($minutes)->seconds($seconds);
}
$total = getDuration(array_shift($durations));
foreach ($durations as $duration) {
$total->add(getDuration($duration));
}
echo $total->cascade()->format('%h:%i:%s'); // 1:15:31