在 PHP 中将两个计算时间相加



我需要一些帮助,我之前已经在 PHP 中计算了每周时间表的时间,而不是我的问题;是否可以将它们全部加在一起?

我尝试使用以下功能,但我不确定这是否有效。目标是每周计算以这种格式总共花费了多少时间。

$time = "18 hours 13 minutes";
$time2 = "47 minutes";
$time3 = "1 hour";
$time4 = "1 hour";
$time5 = "1 hour";
$time6 = "";
$time7 = "";
$max_date=abs(strtotime($time) + strtotime($time2) + strtotime($time3) + strtotime($time4) + strtotime($time5) + strtotime($time6) + strtotime($time7));

因此,它总共应显示 22 小时作为总数。

如果这可能的话?

您可以使用

DateTime对象执行此操作。我们使用当前时间创建两个相同的对象,然后使用 modify 方法将每个时间变量添加到其中一个对象中。然后,我们可以取两个对象之间的差异(创建一个DateInterval对象(,并以与输入相同的格式输出该对象的值:

$start = new DateTime();
$end = clone($start);
if (!empty($time)) $end->modify("+$time");
if (!empty($time2)) $end->modify("+$time2");
if (!empty($time3)) $end->modify("+$time3");
if (!empty($time4)) $end->modify("+$time4");
if (!empty($time5)) $end->modify("+$time5");
if (!empty($time6)) $end->modify("+$time6");
if (!empty($time7)) $end->modify("+$time7");
$total = $end->diff($start);
echo $total->format('%h hours %i minutes');

输出:

22 hours 0 minutes

3v4l.org 演示

最新更新