2015-04-16 111 views
0

我需要计算两个小时之间的差异。例如,08:00:00和09:30:00之间的时间差为1.5小时。计算两次PHP之间的差异(以小时为单位)

我使用下面的代码:

$time1 = '08:00:00'; 
$time2 = '09:30:00'; 
$difference = $time2 - $time1; 
echo $difference; 

,而不是领回1.5如我期望的,我越来越1.我敢肯定,这是格式问题的时刻,有人能轻松提醒我。希望... :)

回答

3

你可以试试我的代码

<?php 
$time1 = strtotime('08:00:00'); 
$time2 = strtotime('09:30:00'); 
$difference = round(abs($time2 - $time1)/3600,2); 
echo $difference; 

注:上面的代码将四舍五入到分钟。

0
<?php 
    $time1 = '08:00:00'; 
    $time2 = '09:30:00'; 
    $array1 = explode(':', $time1); 
    $array2 = explode(':', $time2); 

    $minutes1 = ($array1[0] * 60.0 + $array1[1]); 
    $minutes2 = ($array2[0] * 60.0 + $array2[1]); 

    echo $diff = $minutes1 - $minutes2.' Minutes'; 
?> 
+0

把代码分解成这样很好,但是很好解释这是如何解决问题中舍入问题的。 – Taegost

相关问题