PHP计算两个时间的小时差不生效,返回结果为0如何解决
问题原因
- 核心错误:
date()函数返回值为字符串类型,直接对G:i:s格式的时间字符串做减法运算时,PHP会将字符串强制转换为整型,仅保留开头到第一个冒号前的小时数值,分钟、秒的数值会被直接丢弃。如果两个时间的小时数相同,减法结果就为0,和你遇到的输出现象完全匹配。 - 逻辑冗余:
strtotime()本身返回的就是Unix时间戳(整型,单位为秒),无需转成时间字符串后再做差值计算。
修复方案
直接使用两个时间的原始时间戳计算差值即可,示例代码如下:
// 读取数据库存储的12小时制时间,直接转为时间戳 $timeInTimestamp = strtotime($row['timein']); $timeOutTimestamp = strtotime($row['timeout']); // 计算秒差后转换为小时,保留两位小数 $difference = round(abs($timeOutTimestamp - $timeInTimestamp) / 3600, 2); echo $difference;
如果需要兼容异常场景,可以增加时间戳有效性判断,避免原始时间格式错误导致计算异常:
$timeInTimestamp = strtotime($row['timein']); $timeOutTimestamp = strtotime($row['timeout']); if ($timeInTimestamp && $timeOutTimestamp) { $difference = round(abs($timeOutTimestamp - $timeInTimestamp) / 3600, 2); echo $difference; } else { echo "时间格式错误"; }
内容的提问来源于stack exchange,提问作者dingu da
相关产品推荐
相关产品推荐

