开发者

PHP Time Arithmetic

I have two times in my database:

$time1 = "02:00:03";
$time2 = "04:00:04";

and I want to make add them $time1 + $time2 what is the best way to do that?

I have no problem with the diference cause I can do something like this:

$end = new DateTime($开发者_运维百科this->hora_final);
$start = new DateTime($this->hora_inicio);
$diff = $end->diff($start);

$diff->format('%H:%I:%S');

and it works perfectly... but i can't seem to find a way to add them... any ideas?

Regards


DateTime::add(). It really doesn't make much sense to add two dates, thus you cannot treat $time2 as DateTime, to add it to time1. Usually you would say something like 01.04. + 2 days, but not 01.04. + 02.00. The method accepts an object of type DateInterval. To create it I suggest to use something like

list($hour, $min, $second) = explode(':', $time2);
$interval = new DateInterval("PT{$hour}H{$min}M{$second}S");

Now you should be able to add the interval to the date

$x = new DateTime($time1);
$y = $x->add($interval);

(untested)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜