时差显示一个小时太多

时间:2014-04-14 21:11:48

标签: php time

我正在尝试计算两个时间戳之间的时差。在这里看了一会儿之后我找到了这个解决方案:

$start = strtotime(10:00:00);
$end = strtotime(10:30:00);
$diff = ($end - $start);

echo 'Time 1: '.date('H:i:s', $start).'<br>';
echo 'Time 2: '.date('H:i:s', $end).'<br>';
echo 'Diff: '.date('H:i:s', $diff);

似乎工作,时间1和时间2显示正确的时间,但差异显示01:30:00,而不是00:30:00。我已经尝试设置正确的时区但它没有帮助。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

参考Dates diff in PHP

$date1 = "2013-08-11";
$date2 = "2012-07-12";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

//or simply
//echo "difference " . $interval->days . " days ";

注意

It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier.

答案 1 :(得分:0)

当您需要将秒格式化为HH时:MM:SS不使用date()函数,因为它根据当前时区格式化时间戳。如果您使用gmadate()格式化时间,您的问题将得到解决:

echo 'Diff: ' . gmdate('H:i:s', $diff);

将秒数转换为HH:MM:SS格式:https://stackoverflow.com/a/20870843/67332