在php中加入时间

I want to add up time in php but after hours of google'ing and trying out im still unable to find a solution.

my values are:

$newTotal = '00:45:00';
$oldTotal = '00:16:00';

I want to add those two up which make 01:01:00.

Can you give me an example i'm getting really desperate! :p

thanks in advance,

keep a start date for minimum error.

<?php
$origin   = '00:00:00';
$newTotal = '00:45:00';
$oldTotal = '00:16:00';

$added = strtotime($newTotal) + (strtotime($oldTotal) - strtotime($origin));

echo date('H:i:s', $added );

output :

01:01:00

Note, if your time is more than 23:59:59 after adding, you will get wrong result.

If these values always look like that, you could break them down with a substr()

$hours1 = substr($newTotal, 0, 2);

etc. And then simply add up the seconds, do a divide and mod and bubble up to the hours, and voila!

$secondstotal = $seconds1+$seconds2; 
$restseconds = $secondstotal % 60;
$minutesfromseconds = floor($restseconds / 60);

$minutestotal = $minutes1+$minutes2+$minutesfromseconds;

etc.

Use strtotime() to turn them into Unix timestamps, then add them as integers:

$newTotal = '00:45:00';
$oldTotal = '00:16:00';

$total = strtotime($newTotal) + strtotime($oldTotal);

To format it as hh:mm:ss again, use date():

echo date('H:i:s', $total);

This gives:

01:01:00

Another solution without time function:

function sumtotal($a,$b) {
    $i = explode(':',$a);
    $j = explode(':',$b); // 0hh:1mm:2ss
    $k = array(0,0,0,0); // 0days:1hours:2minutes:3seconds
    $k[3] = $i[2]+$j[2];
    $k[2] = (int)($k[3]/60)+$i[1]+$j[1];
    $k[1] = (int)($k[2]/60)+$i[0]+$j[0];
    $k[0] = (int)($k[1]/24);
    $k[3] %= 60;
    $k[2] %= 60;
    $k[1] %= 24;
    if ($k[3]<10) $k[3] = '0'.$k[3];
    if ($k[2]<10) $k[2] = '0'.$k[2];
    if ($k[1]<10) $k[1] = '0'.$k[1];
    return $k[0].' days : '.$k[1].' hours : '.$k[2].' minutes : '.$k[3].' seconds';
}

$newTotal = '01:45:21';
$oldTotal = '03:16:56';
echo sumtotal($newTotal,$oldTotal); // result:  0 days : 05 hours : 02 minutes : 17 seconds