user3242861
user3242861

Reputation: 1929

Php - How to sum hours?

I have to hours, 11:00:00 and 06:30:00 and I want to sum this 2 values, 17:30:00.

I try to do that with carbon but it returns me a wrong value!

$startTime1 = Carbon::createFromFormat('H:i:s', '11:00:00');
$startTime2 = Carbon::createFromFormat('H:i:s', '06:30:00');

$total_in_seconds = $startTime1->timestamp + $startTime2->timestamp;
$totalInterventions = Carbon::createFromTimestamp($total_in_seconds)->format('h:i:s');

But it returns me 05:30, the difference between this 2 hours.

Thank you

Upvotes: 1

Views: 208

Answers (2)

Zaheer Abbas
Zaheer Abbas

Reputation: 144

This code will do trick for you.

        $time = new Carbon($startTime1);
        $startTime2=new Carbon($startTime2);
        $time->diffForHumans($startTime2);

Upvotes: 1

Morten Bork
Morten Bork

Reputation: 1632

$startTime1 = Carbon::createFromFormat('H:i:s', '11:00:00');
$startTime2 = Carbon::createFromFormat('H:i:s', '06:30:00');

$total_in_seconds = $startTime1->timestamp + $startTime2->timestamp;
$totalInterventions = Carbon::createFromTimestamp($total_in_seconds)-

>format('h:i:s'); <--- This would likely cause you an issue.

Try instead

>format('H:i:s');

Upvotes: 2

Related Questions