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 扩展,它实际上是可能的(至少在某种程度上)。