在php中添加两个时间值

    $test=strtotime("06:30:00")+strtotime("03:00:00");

    echo gmdate("H:i:s", $test);

This gives the wrong answer ( 23:01:44 ).

    $test=strtotime("06:30:00")-strtotime("03:00:00");

    echo gmdate("H:i:s", $test);

while subtracting same code gives me the right answer( 03:30:00 ).

You should do this:

<?
echo date("H:i:s", strtotime("06:30:00 + 3 hour"));
echo date("H:i:s", strtotime("06:30:00 - 3 hour"));
?>

Your logic is wrong. If you'll act like in 1-st sample, you'll sum two timestamps as they are (i.e. starting from 0) - so you'll count previous time twice. If you are subtracting them, however, you're getting 'expected' result because each operand's previous period eliminates another.

But that's not how it's supposed to work. You should use DateTime API to work with dates and periods in PHP.

I came across a similar problem, and wrote a small function to convert times (formatted in a variety of ways) to seconds. It's obviously then trivial to add the seconds together.

function getSeconds($s) {
    $s = str_replace('h',':',$s);
    $s = str_replace(',','.',$s);

    $a = explode(':',$s);
    $n = count($a);

    if ($n==1)
        return $a[0]; //just seconds

    if ($n==2)
        return $a[1] + 60 * $a[0]; //minutes and seconds

    if ($n==3)
        return $a[2] + 60 * $a[1] + 3600 * $a[0]; //hours minutes and seconds
}

Works for the following formats:

 12
 12.34
 12:34 (will assume mm:ss in this format)
 12:34.56
 12:34,56
 12:34:56.78
 12h34:56,78
 $date1 = strtotime('2012-05-01 12:00:00');
 $date2 = time();
 $subTime = $date1 - $date2;
 $y = ($subTime/(60*60*24*365));
 $d = ($subTime/(60*60*24))%365;
 $h = ($subTime/(60*60))%24;
 $m = ($subTime/60)%60;

 echo "Difference between ".date('Y-m-d H:i:s',$date1)." and ".date('Y-m-d H:i:s',$date2)." is:
";
 echo $y." years
";
 echo $d." days
";
 echo $h." hours
";
 echo $m." minutes
";