以 2 24 小时时间格式计算工作小时数 PHP
Calculate Number of hours worked in 2 24 hour time format PHP
您好,我有一个 24 小时制的变量,我想计算工作的小时数。但我得到负值和错误值
我正在使用 PHP,这是我的代码
$endtime = date( 'g:i A', strtotime( $itInfo['endTime'] ) );
$startTime = date( 'g:i A', strtotime( $itInfo['startTime'] ) );
$timeDiff = (strtotime($endtime) - strtotime($startTime))/60/60;
$total = strtotime($endtime) - strtotime($startTime);
$hours = floor($total / 60 / 60);
$minutes = round(($total - ($hours * 60 * 60)) / 60);
echo "FROM ".$itInfo['startTime']." TO ".$itInfo['endTime']." (".$hours.'.'.$minutes."hours)";`
这是 FROM 22:00 TO 03:00 (-19.0hours) 的输出,错误的输出应该是 5 小时。
试试这个:
$timeDiff = strtotime($itInfo['endTime']) - strtotime($itInfo['startTime']);
echo substr('00'.($timeDiff / 3600 % 24),-2)
.':'. substr('00'.($timeDiff / 60 % 60),-2)
.':'. substr('00'.($timeDiff % 60),-2);
正如其他人所说,最好使用时间戳。但是使用您当前的代码,您应该能够在 echo
:
之前添加它
if ($itInfo['startTime'] > $itInfo['endTime']) {
$hours = 24 - $hours;
}
这将是:24 - 19 = 5
。
此外,请务必在您的 $total
变量中添加 abs()
:
$total = abs(strtotime($endtime) - strtotime($startTime));
您好,我有一个 24 小时制的变量,我想计算工作的小时数。但我得到负值和错误值
我正在使用 PHP,这是我的代码
$endtime = date( 'g:i A', strtotime( $itInfo['endTime'] ) );
$startTime = date( 'g:i A', strtotime( $itInfo['startTime'] ) );
$timeDiff = (strtotime($endtime) - strtotime($startTime))/60/60;
$total = strtotime($endtime) - strtotime($startTime);
$hours = floor($total / 60 / 60);
$minutes = round(($total - ($hours * 60 * 60)) / 60);
echo "FROM ".$itInfo['startTime']." TO ".$itInfo['endTime']." (".$hours.'.'.$minutes."hours)";`
这是 FROM 22:00 TO 03:00 (-19.0hours) 的输出,错误的输出应该是 5 小时。
试试这个:
$timeDiff = strtotime($itInfo['endTime']) - strtotime($itInfo['startTime']);
echo substr('00'.($timeDiff / 3600 % 24),-2)
.':'. substr('00'.($timeDiff / 60 % 60),-2)
.':'. substr('00'.($timeDiff % 60),-2);
正如其他人所说,最好使用时间戳。但是使用您当前的代码,您应该能够在 echo
:
if ($itInfo['startTime'] > $itInfo['endTime']) {
$hours = 24 - $hours;
}
这将是:24 - 19 = 5
。
此外,请务必在您的 $total
变量中添加 abs()
:
$total = abs(strtotime($endtime) - strtotime($startTime));