1
$time1 = "01:00";
$time2 = "04:55";
list($hours1, $minutes1) = explode(':', $time1);
$startTimestamp = mktime($hours1, $minutes1);

list($hours2, $minutes2) = explode(':', $time2);
$endTimestamp = mktime($hours2, $minutes2);

$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));

echo $hours.':'.$minutes;
exit;

输出 4:55,应该是 3:55 吗?

这里有什么问题?如果是 01:00 和 02:00,它可以正常工作,但不是上面的?

4

4 回答 4

6

使用floor代替round...

于 2012-09-26T15:15:32.420 回答
0

或者只是转换为整数。

$hours = (int) ($seconds / (60 * 60));
于 2012-09-26T15:17:40.737 回答
0

PHP 可以为您完成的计算过多,同时也减少了出错的可能性

$time1 = Datetime::createFromFormat("h:i", "01:00");
$time2 = Datetime::createFromFormat("h:i", "04:55");

$diff = $time1->diff($time2);
var_dump($diff->format("%h %i"));

输出

string '3:55' (length=4)
于 2012-09-26T15:20:01.330 回答
0

您还可以使用以下方法节省一些时间strtotime

$time1 = strtotime("01:00");
$time2 = strtotime("04:55");

$seconds = $time2-$time1;
$minutes = ($seconds / 60) % 60;
$hours = floor($seconds / (60 * 60));

echo $hours.':'.$minutes;

如前所述, usingfloor将产生您需要的结果:

结果

3:55
于 2012-09-26T15:21:20.580 回答