How to add two 'time' datatypes in laravel?

Member

by dana , in category: PHP Frameworks , 4 months ago

How to add two 'time' datatypes in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 4 months ago

@dana 

To add two 'time' datatypes in Laravel, you can create two Carbon instances and then add them together. Here's an example:

1
2
3
4
5
6
$time1 = Carbon::createFromTimeString('12:00:00');
$time2 = Carbon::createFromTimeString('03:30:00');

$sum = $time1->addHours($time2->hour)->addMinutes($time2->minute)->addSeconds($time2->second);

echo $sum->toTimeString();


In this example, we create two Carbon instances for the two times we want to add together, '12:00:00' and '03:30:00'. We then use the addHours(), addMinutes(), and addSeconds() methods to add the hours, minutes, and seconds of the second time to the first time, respectively.


Finally, we can output the sum in 'time' format using the toTimeString() method.