PHP时间算术 [英] PHP Time Arithmetic
问题描述
$ time1 =02:00:03;
$ time2 =04:00:04;
,我想添加他们 $ time1 + $ time2
最好的方法是什么?
我没有任何问题,因为我可以做这样的事情:
$ end = new DateTime($ this-> hora_final);
$ start = new DateTime($ this-> hora_inicio);
$ diff = $ end-> diff($ start);
$ diff->格式('%H:%I:%S');
它的工作完美...但我似乎找不到一种方法来添加它们。 ..任何想法?
注意
DateTime :: add()
。添加两个日期真的没有什么意义,因此您不能将 $ time2
视为 DateTime
添加它到 time1
。通常你会发现像 01.04。 + 2天
,但不是 01.04。 + 02.00
。该方法接受类型为 DateInterval
的对象。要创建它,我建议使用类似
列表($ hour,$ min,$ second)= explode(':' ,$ time2);
$ interval = new DateInterval(PT {$ hour} H {$ min} M {$ second} S);
现在您应该可以将间隔添加到日期
$ x = new DateTime($ time1);
$ y = $ x-> add($ interval);
(未经测试)
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)
这篇关于PHP时间算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!