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";
完整示例/(演示):
$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";
您可能还需要考虑查看如何存储其值,然后从中扩展以执行自己的计算。下面的示例(Demo)很粗略,它没有考虑倒置的东西,它没有(重新)将$days
设置为false
,我没有在创建时检查/测试周期说明符的ISO规范,但我认为这足以表明这个想法:DateInterval
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扩展,它实际上是可能的(至少是某种程度上)。