在PHP中没有得到正确的时差

时间:2012-09-26 15:14:14

标签: php

$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 个答案:

答案 0 :(得分:6)

使用floor代替round ...

答案 1 :(得分:0)

或者只是转换为整数。

$hours = (int) ($seconds / (60 * 60));

答案 2 :(得分: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)

答案 3 :(得分: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;

如上所述,使用floor将产生您需要的结果:

<强>结果

3:55