使用php在数据库表中开始时间和结束时间,我正在计算开始时间和结束时间之间的差异,以获得任务的总持续时间总和。
我使用以下方法:
foreach ($task->timers as $time ) {
$start_date = new DateTime($time->date.' '.$time->start_time);
$end_date = new DateTime($time->date.' '.$time->end_time);
$times[] = date_diff($end_date, $start_date);
}
然后按如下方式遍历上面的数组;
foreach ($times as $timer) {
$minutes = strlen($timer->i);
if($minutes == 1) {
$minutes = '0'.$timer->i;
} else {
$minutes = $timer->i;
}
$o[] = $timer->h.':'.$minutes.':'.$timer->s;
}
然后我得到如下数组;
array(2) { [0]=> string(7) "0:54:17" [1]=> string(7) "0:01:26" }
现在我想将这两个值加在一起以获得总持续时间,我正在尝试按以下方式执行此操作;
$totalTime = array_sum($o);
然而这又回来了:
int(0);
任何想法如何计算两个持续时间的总持续时间?
答案 0 :(得分:2)
不幸的是array_sum
不能对字符串起作用,只对数值有效(因为PHP显然不知道如何用字符串进行数学运算)。你可以简单地这样加:
$hrs = 0;
$mins = 0;
$secs = 0;
foreach ($o as $time) {
// Let's take the string apart into separate hours, minutes and seconds
list($hours, $minutes, $seconds) = explode(':', $time);
$hrs += (int) $hours;
$mins += (int) $minutes;
$secs += (int) $seconds;
// Convert each 60 minutes to an hour
if ($mins >= 60) {
$hrs++;
$mins -= 60;
}
// Convert each 60 seconds to a minute
if ($secs >= 60) {
$mins++;
$secs -= 60;
}
}
现在,您将$mins
的值为55,$secs
的值为43。
您可以再次以任何所需的格式打印它们,例如:
echo sprintf('%d:%d:%d', $hrs, $mins, $secs);
哪会导致0:55:43
。