我想添加两个日期间隔,以小时和分钟为单位计算总持续时间,实际上我要执行加法运算,如下所示:
$a = new DateTime('14:25'); $b = new DateTime('17:30'); $interval1 = $a->diff($b); echo "interval 1 : " . $interval1->format("%H:%I"); echo "<br />"; $c = new DateTime('08:00'); $d = new DateTime('13:00'); $interval2 = $c->diff($d); echo "interval 2 : " . $interval2->format("%H:%I"); echo "<br />"; echo "Total interval : " . $interval1 + $interval2;
任何想法如何执行这种类型的间隔加法来获取PHP中总小时和分钟格式的两个间隔之和
PHP没有运算符重载*,因此+有了对象,PHP会尝试先将其转换为字符串,但DateInterval不支持:
+
DateInterval
interval 1: 03:05 interval 2: 05:00 Total interval : 08:05
相反,您需要创建一个新DateTime对象,然后使用该add函数添加间隔,最后将差异显示到参考点:
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";
您可能还需要考虑查看如何DateInterval存储其值,然后从中扩展以自己计算。以下示例(Demo)很粗糙,它没有考虑到倒置的东西,也没有($days``false重置为,并且我还没有在创建时检查/测试周期说明符的ISO规范,但我认为这足以显示想法:
$days``false
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扩展,实际上是有可能的(至少是排序的)。