PHP switch时间差计算代码:??占位部分逻辑实现求助
PHP switch时间分支的间隔计算与代码修正
原代码存在的基础问题
- 对
date()函数的参数顺序存在误用:date()首个参数为输出格式字符串,第二个参数为可选的Unix时间戳,原代码将当前时间字符串作为格式传入,会导致输出结果异常 - 所有间隔秒数的计算不需要手动拆分时分秒做换算,直接用两个时间点的Unix时间戳做差值,即可得到准确的间隔秒数,还能规避跨天计算、时区转换带来的误差
三个占位位置的具体实现逻辑
- 第一个分支(当前小时在8~13点区间):计算到当日13:00的间隔秒数
对应计算式:strtotime(date("Y-m-d 13:00:00")) - time() - 第二个分支(当前小时在12~18点区间):计算到当日19:00的间隔秒数
对应计算式:strtotime(date("Y-m-d 19:00:00")) - time() - 第三个分支(当前小时在17~22点区间):计算到次日9:00的间隔秒数,直接拼接次日的9点时间戳做差值即可
对应计算式:strtotime(date("Y-m-d 09:00:00", strtotime("+1 day"))) - time()
修正后的完整可运行代码
<?php $currentTs = time(); $nuUur = date("H", $currentTs); switch(true) { case $nuUur > 8 && $nuUur < 13: // 到当日13:00的间隔秒数 $aantSecErbij = strtotime(date("Y-m-d 13:00:00", $currentTs)) - $currentTs; $weerOp = date("Y-m-d H:i:s", $currentTs + $aantSecErbij); echo $weerOp; break; case $nuUur > 12 && $nuUur < 18: // 到当日19:00的间隔秒数 $aantSecErbij = strtotime(date("Y-m-d 19:00:00", $currentTs)) - $currentTs; $weerOp = date("Y-m-d H:i:s", $currentTs + $aantSecErbij); echo $weerOp; break; case $nuUur > 17 && $nuUur < 22: // 到次日9:00的间隔秒数 $targetTs = strtotime("+1 day", strtotime(date("Y-m-d 09:00:00", $currentTs))); $aantSecErbij = $targetTs - $currentTs; $weerOp = date("Y-m-d H:i:s", $currentTs + $aantSecErbij); echo $weerOp; break; } ?>
补充说明
- 上述时间戳差值计算方式不需要手动拆算小时、分钟、秒的换算值,能自动处理时区、夏令时调整这类边角场景的计算误差
- 当前分支判断仅覆盖了9点~21点的时段,早于9点、晚于22点的时段没有匹配分支,可根据实际业务需求补充对应逻辑
内容的提问来源于stack exchange,提问作者Erik
相关产品推荐
相关产品推荐

