PHP没有操作符重载*所以使用对象使PHP尝试将其转换为字符串首先,但DateInterval不支持:
interval 1: 03:05
interval 2: 05:00
Total interval : 08:05
相反,您需要创建一个新的DateTime对象,然后使用add函数添加间隔,最后显示与参考点的差异:
$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
echo "Total interval : ", $f->diff($e)->format("%H:%I"), "\n";
完整的例子/(Demo):
$a = new DateTime('14:25');
$b = new DateTime('17:30');
$interval1 = $a->diff($b);
echo "interval 1: ", $interval1->format("%H:%I"), "\n";
$c = new DateTime('08:00');
$d = new DateTime('13:00');
$interval2 = $c->diff($d);
echo "interval 2: ", $interval2->format("%H:%I"), "\n";
$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
echo "Total interval : ", $f->diff($e)->format("%H:%I"), "\n";
您可能还想考虑如何使用DateInterval存储其值,然后从其中扩展以进行自己的计算。以下示例(Demo)是粗糙的,它没有考虑到the inverted thingy,它是not (re)set $days to false,我没有检查/测试了the period specifier on creation的ISO规范,但我认为足以显示这个想法:
class MyDateInterval extends DateInterval
{
/**
* @return MyDateInterval
*/
public static function fromDateInterval(DateInterval $from)
{
return new MyDateInterval($from->format('P%yY%dDT%hH%iM%sS'));
}
public function add(DateInterval $interval)
{
foreach (str_split('ymdhis') as $prop)
{
$this->$prop += $interval->$prop;
}
}
}
$a = new DateTime('14:25');
$b = new DateTime('17:30');
$interval1 = $a->diff($b);
echo "interval 1: ", $interval1->format("%H:%I"), "\n";
$c = new DateTime('08:00');
$d = new DateTime('13:00');
$interval2 = $c->diff($d);
echo "interval 2: ", $interval2->format("%H:%I"), "\n";
$e = MyDateInterval::fromDateInterval($interval1);
$e->add($interval2);
echo "Total interval: ", $e->format("%H:%I"), "\n";
*如果你编写一个PHP扩展名,它实际上是可能的(至少是排序的)。