user0129e021939232
user0129e021939232

Reputation: 6355

php addition of multiple durations to get total duration

start time and end time in a database table using php and I am calculating the difference between the start time and end time to get the total duration total of a task.

I am using the following method:

 foreach ($task->timers as $time ) {
    $start_date = new DateTime($time->date.' '.$time->start_time);
    $end_date = new DateTime($time->date.' '.$time->end_time);
    $times[] = date_diff($end_date, $start_date);
   }

I then loop through the array above as follows;

  foreach ($times as $timer) {
        $minutes = strlen($timer->i);
        if($minutes == 1) {
            $minutes = '0'.$timer->i;
        } else {
            $minutes = $timer->i;
        }
        $o[] = $timer->h.':'.$minutes.':'.$timer->s;
    }

I then get an array as follows;

array(2) { [0]=> string(7) "0:54:17" [1]=> string(7) "0:01:26" }

Now I want to add those two values together to get the total duration and I'm attempting to do this as follows;

    $totalTime = array_sum($o);

however this comes back as :

int(0);

Any ideas how I can calculate the total duration of two durations??

Upvotes: 3

Views: 1004

Answers (1)

Oldskool
Oldskool

Reputation: 34837

Unfortunately array_sum does not work on strings, only on numerical values (because PHP has no clue how to do math with strings obviously). You could simply add up like this:

$hrs = 0;
$mins = 0;
$secs = 0;

foreach ($o as $time) {
    // Let's take the string apart into separate hours, minutes and seconds
    list($hours, $minutes, $seconds) = explode(':', $time);

    $hrs += (int) $hours;
    $mins += (int) $minutes;
    $secs += (int) $seconds;

    // Convert each 60 minutes to an hour
    if ($mins >= 60) {
        $hrs++;
        $mins -= 60;
    }

    // Convert each 60 seconds to a minute
    if ($secs >= 60) {
        $mins++;
        $secs -= 60;
    }
}

Now you will have $mins with a value of 55 and $secs with a value of 43. You can print them in any desired format again, like:

echo sprintf('%d:%d:%d', $hrs, $mins, $secs);

Which would result in 0:55:43.

Upvotes: 2

Related Questions