在PHP中总结两个不同的DateTime

时间:2018-03-15 08:53:45

标签: php

我的代码:

$one = new DateTime("2018-03-15 11:53:13");
$two = new DateTime("2018-03-15 13:53:00");
$diff = $one->diff($two);
$three = new DateTime("2018-03-15 11:52:55");
$four = new DateTime("2018-03-16 11:52:57");
$difftwo = $three->diff($four);
$day = $diff->format('%H:%I:%S');
$day2 = $difftwo->format('%H:%I:%S');

$secs = strtotime($day2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($day) + $secs);

echo $result;


- $ day = 01:59:47
- $ day2 = 00:00:02和1天
结果: 01:59:49 但我想表明: 1 01:59:49 (1是$ day2的结果)

有人可以帮我找到解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以创建2个新的相同日期。在其中一个中,add你的2个间隔。

然后您可以使用DateInterval对象来获取您的值:

$one = new DateTime('2018-03-15 11:53:13');
$two = new DateTime('2018-03-15 13:53:00');
$diff = $one->diff($two);

$three = new DateTime('2018-03-15 11:52:55');
$four = new DateTime('2018-03-16 11:52:57');
$difftwo = $three->diff($four);

$d1 = new DateTime(); // Now
$d2 = new DateTime(); // Now
$d1->add($diff); // Add 1st interval
$d1->add($difftwo); // Add 2nd interval

// diff between d2 and d1 gives total interval
echo $d2->diff($d1)->format('%d %H:%I:%S') ; 

输出:

1 01:59:49