PHP - 小时差异(HH:MM格式)

Nic*_*ick 3 php time

我正在尝试计算在这里工作的人的班次模式,从结束时间减去开始时间大部分工作,但如果他们在一夜之间工作则不行.例如,工作的10pm to 6am人将显示为:

22:00 - 06:00
Run Code Online (Sandbox Code Playgroud)

我想要回归8 hours,但我无法弄清楚这样做的最佳方法.

令人讨厌的是,我将不得不在Javascript中做同样的事情,所以我希望我能够理解这个逻辑.在这种情况下,从另一个中夺走一个日期不起作用......

非常感谢任何帮助,谢谢!

And*_*aal 6

function timeDiff($firstTime,$lastTime) {
    $firstTime=strtotime($firstTime);
    $lastTime=strtotime($lastTime);
    $timeDiff=$lastTime-$firstTime;
    return $timeDiff;
}

echo (timeDiff("10:00","12:00")/60)/60;
Run Code Online (Sandbox Code Playgroud)

最初在这里写道:http://andrewodendaal.com/php-hours-difference-hhmm-format/


Jon*_*Jon 5

老派,有字符串操作和数学:

$input = '22:00 - 06:00';
preg_match('/(\d+):(\d+)\D*(\d+):(\d+)/', $input, $matches);
list(, $startHour, $startMin, $endHour, $endMin) = $matches;
$totalMinutes = ($endHour * 60 + $endMin - $startHour * 60 + $startMin + 1440) % 1440;
$hours = floor($totalMinutes / 60);
$mins = $totalMinutes % 60;

echo "works for $hours hours, $mins minutes";
Run Code Online (Sandbox Code Playgroud)

有日期/时间功能:

$input = '22:00 - 06:00';
list($start, $end) = array_map('trim', explode('-', $input));
$start = new DateTime($start.'+00:00');
$end = new DateTime($end.'+00:00');
if ($start > $end) $start->sub(new DateInterval('P1D'));
$interval = $end->diff($start);
echo "works for ".$interval->h." hours, ".$interval->m." minutes";
Run Code Online (Sandbox Code Playgroud)

使用日期/时间功能的任何解决方案的恶魔陷阱:

如果你没有明确指定的偏移量$start$end,我们正在谈论的是夜班,和代码在哪里夏令时开始或结束的结果会以任何的DST偏移量是被关闭之日起执行.

这适用于使用任何解决方案DateTime,strtotime等等.