1

我有两个DateTime对象。

$time1 = new DateTime('01:04:00');
$time2 = new DateTime('00:13:22');

这两个的加法将是:01:17:22。我该怎么做?

4

3 回答 3

4

A "time of day" is not the same thing as a "duration of time". It doesn't makes sense to add together two time of day values - regardless of platform or language. Think about it - what does "11:00 PM" + "4:00 AM" equal? It's a nonsensical question.

You should be thinking about PHP's DateInterval class, not the DateTime class.

It should be noted that if you follow the examples on the dup posts of using strtotime it will work only when each individual input, and the final result, are all under 24 hours. Why? Because that's the maximum amount of time allowed in a standard day. That's the consequence of mixing "time of day" with "duration of time".

This should work for you:

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('01:04:00');
$interval2 = time_to_interval('00:13:22');
$interval3 = add_intervals($interval1,$interval2);

echo format_interval_hhmmss($interval3);

Note that the choice of value for $zerodate isn't really all that important. It's just that some reference point is required, since PHP doesn't provide operations directly on DateInterval.

Also note that the the DateInterval::format function doesn't have a formatter to get you total number of hours inclusive of days, so if there's any chance the total could be 24 hours or more, then you have to format that part yourself, like I showed in the format_interval_hhmmss function.

Also note that my PHP skills are not all that great, so there may be a more efficient way to write these functions.

于 2013-09-16T20:08:11.563 回答
2
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;
}
于 2013-09-18T14:47:54.007 回答
1

唯一的内置 DateTime 加/减方法需要使用 DateInterval。例如

$t1 = new DateTime('01:04:33');
$new = $t1->add(new DateInterval('PT13M22S'));
                                    ^^^^^^---13 minutes, 22 seconds

但是,请注意,由于 DateTime 对 DATES 和时间都有效,因此您不能像这样拼凑两次并期望获得可靠的结果。考虑一下如果您在恰好跨越夏令时边界或跨越日边界等的间隔上进行添加会发生什么......

于 2013-09-16T20:11:22.373 回答