如何获得(小时和分钟)格式的时间总和值?

时间:2014-03-27 05:42:14

标签: php time timestamp

我想添加两个time()并获得结果。例如我得到time1为1395897426,time2为1395897487现在我想在变量time3中添加这两个时间并将其转换为小时和分钟

    <?php 
    $time1 =time();
    $time2 = time();
    $time3 = $time1+$time2;
    echo $time3;
    ?>

实际上我正在使用函数来查找时差。 function time_diff($ start,$ end)

{
       $time1 = date('H:i',$start);
       $time2 = date('H:i',$end);
       list($hours, $minutes) = explode(':', $time1);
       $startTimestamp = mktime($hours, $minutes);

       list($hours, $minutes) = explode(':', $time2);
       $endTimestamp = mktime($hours, $minutes);

       $seconds = $endTimestamp - $startTimestamp;
       $minutes = ($seconds / 60) % 60;
       $hours = round($seconds / (60 * 60));
       echo "<b>$hours</b> hours and <b>$minutes</b> minutes";
}

1 个答案:

答案 0 :(得分:0)

让DateTime为你完成所有工作,而不是摆弄它。

$time1 = new DateTime;
$time2 = new DateTime("2014-03-25 06:52:21");

$interval = $time2->diff($time1);

// Get number of days and multiply by 24 hours
$elapsed['h'] = $interval->format('%a') * 24;
// Then add in hours
$elapsed['h'] += $interval->format('%h');

// Minutes
$elapsed['m'] = $interval->format('%i');

echo $elapsed['h'] . ' hours and ' . $elapsed['m'] . ' minutes';
// produces 41 hours and 3 minutes