I need some help, I have already previously calculated my times for a weekly timesheet in PHP, not my question; is it possible to add these all together?

I tried to use the following function but i'm not sure this works. The aim is for each week to calculate how much time is spent in total in this format.

$time = "18 hours 13 minutes";
$time2 = "47 minutes";
$time3 = "1 hour";
$time4 = "1 hour";
$time5 = "1 hour";
$time6 = "";
$time7 = "";

$max_date=abs(strtotime($time) + strtotime($time2) + strtotime($time3) + strtotime($time4) + strtotime($time5) + strtotime($time6) + strtotime($time7));

So in all it should show 22 hours as the total.

Thats if this is possible?

1 Answers

Nick On

You can do this using DateTime objects. We create two identical objects using the current time, then we use the modify method to add each of the time variables to one of them. We can then take the difference between the two objects (creating a DateInterval object) and output the value of that in the same format as the inputs:

$start = new DateTime();
$end = clone($start);

if (!empty($time)) $end->modify("+$time");
if (!empty($time2)) $end->modify("+$time2");
if (!empty($time3)) $end->modify("+$time3");
if (!empty($time4)) $end->modify("+$time4");
if (!empty($time5)) $end->modify("+$time5");
if (!empty($time6)) $end->modify("+$time6");
if (!empty($time7)) $end->modify("+$time7");

$total = $end->diff($start);
echo $total->format('%h hours %i minutes');


22 hours 0 minutes

Demo on 3v4l.org