Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP计算两次之间的差异(以小时为单位)_Php - Fatal编程技术网

用PHP计算两次之间的差异(以小时为单位)

用PHP计算两次之间的差异(以小时为单位),php,Php,我需要计算两次的时间差。例如,08:00:00和09:30:00之间的差值为1.5小时 我正在使用下面的代码: $time1 = '08:00:00'; $time2 = '09:30:00'; $difference = $time2 - $time1; echo $difference; 我得到的不是我期望的1.5分,而是1分。我相信这是一个时间格式的问题,有人可以很容易地建议我。希望……:) 你可以试试我的代码 <?php $time1 = strtotime('08:00:00'

我需要计算两次的时间差。例如,08:00:00和09:30:00之间的差值为1.5小时

我正在使用下面的代码:

$time1 = '08:00:00';
$time2 = '09:30:00';
$difference = $time2 - $time1;
echo $difference;
我得到的不是我期望的1.5分,而是1分。我相信这是一个时间格式的问题,有人可以很容易地建议我。希望……:)

你可以试试我的代码

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


这样分解代码很好,但最好解释一下如何解决问题中的舍入问题。分解时间字符串时,它将有一个新字符串,而不是数组,因此此代码将导致错误
<?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';
?>