Laravel中date与strtotime函数时区问题及时间差计算修复
问题:时区设置为Asia/Kolkata后,时间差格式化出现+5:30偏差
我已经在app.php中将应用时区设置为Asia/Kolkata,配置代码如下:
/* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'Asia/Kolkata',
但计算两个时间差值并格式化时,输出结果出现+5:30的偏差。示例代码:
$inTime = "10:08:00"; $outTime = "10:08:00"; $spentTime = strtotime($outTime) - strtotime($inTime); echo "<pre>"; print_r("out time = ".$outTime); echo "<br>"; print_r("in time = ".$inTime); echo "<br>"; print_r("spent time = ".$spentTime); $spentTime = date('H:i:s', $spentTime); echo "<br>"; print_r("spent time format = ".$spentTime); die;
实际输出:
out time = 10:08:00 in time = 10:08:00 spent time = 0 spent time format = 05:30:00
期望spent time format的结果为00:00:00,该如何解决?
原因分析
strtotime($outTime) - strtotime($inTime)得到的是时间差的秒数,而非有效的Unix时间戳。当用date('H:i:s', 0)格式化秒数0时,PHP会将其解析为Unix时间戳0对应的时区时间——也就是Asia/Kolkata时区下1970年1月1日的05:30:00,这就是偏差的来源。
解决方案
不要用date()函数处理时间差,而是直接基于秒数计算时分秒,或使用DateTime类处理:
方案1:手动计算时分秒
$spentTime = 0; // 替换为实际得到的时间差秒数 $hours = floor($spentTime / 3600); $minutes = floor(($spentTime % 3600) / 60); $seconds = $spentTime % 60; $formattedTime = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds); echo "spent time format = " . $formattedTime;
方案2:使用DateTime类(更推荐)
$inTime = new DateTime("10:08:00"); $outTime = new DateTime("10:08:00"); $interval = $outTime->diff($inTime); echo "spent time format = " . $interval->format('%H:%I:%S');
两种方式都能输出正确的00:00:00结果。
内容的提问来源于stack exchange,提问作者Mukesh Khatri
相关产品推荐
相关产品推荐

