在PHP中添加时间值

时间:2014-12-19 21:46:11

标签: php datetime laravel

我正在尝试添加两个时间值A和B,其中A = 18:00:00这是一个实际时间而B = 00:45:00这只是一个持续时间。通过添加A和B,预期结果应该是18:45:00但由于某种原因我总是得到错误的值。

$newTime = date('H:i:s', strtotime($row->start_time) + strtotime($row->quiz_duration));

1 个答案:

答案 0 :(得分:1)

试试这个:

<?php
function time_to_interval($time) {
    $parts = explode(':',$time);
    return new DateInterval('PT'.$parts[0].'H'.$parts[1].'M'.$parts[2].'S');
}

function add_intervals($a,$b) {
    $zerodate = new DateTime('0000-01-01 00:00:00');
    $dt = clone $zerodate;
    $dt->add($a);
    $dt->add($b);
    return $zerodate->diff($dt);
}

function format_interval_hhmmss($interval){
    $totalhours = $interval->h + ($interval->d * 24);
    return $totalhours.$interval->format(':%I:%S');
}

$interval1 = time_to_interval('18:00:00');
$interval2 = time_to_interval('00:45:00');
$interval3 = add_intervals($interval1,$interval2);

echo format_interval_hhmmss($interval3);

<强>演示:
http://3v4l.org/MlTs5


或者:

function addtime($time1,$time2)
{
    $x = new DateTime($time1);
    $y = new DateTime($time2);

    $interval1 = $x->diff(new DateTime('00:00:00')) ;
    $interval2 = $y->diff(new DateTime('00:00:00')) ;

    $e = new DateTime('00:00');
    $f = clone $e;
    $e->add($interval1);
    $e->add($interval2);
    $total = $f->diff($e)->format("%H:%I:%S");
    return $total;
}

echo addtime('18:00:00','00:45:00');

<强>演示:
http://3v4l.org/A6m1A