在 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
- $day 2 = 00:00:02 和 1 天
结果 : 01:59:49但我想显示:1 01:59:49(1 是 $day 2( 的一天结果

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

您可以创建 2 个新的相同日期。在其中一个中,添加您的 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

最新更新