首页 > 解决方案 > Time() 按 5 分钟选择

问题描述

PHP 函数将 time() 秒转换为时间格式 Hour:Minutes

function secondsToTime($seconds) {
 $dtF = new \DateTime('@0');
 $dtT = new \DateTime("@$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
 return $dtF->diff($dtT)->format('%h:%i');
}

echo secondsToTime(time());

我需要一个函数,例如:

If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50

但是输出以 time() 格式秒显示,所以这样我可以通过 mysql 检查从 time() 格式更新了多少行,如果现在时间是 23:49,那么在过去的 4 分钟内显示 23:45 ...

标签: phpdate

解决方案


您需要对分钟进行四舍五入,然后重新格式化输出日期。

这里隐藏着一些陷阱。正如您最终可以得到 60 分钟(应该是00)和 24 小时(也应该是00)。因此,特别检查到位,以捕捉到这一点。

此外,您获取当前时间的方式非常复杂。获取“现在”获得的值与DateTime()默认值相同。

function secondsToTime() {
    $now      = new \DateTime();
    $cminutes = $now->format('i');
    $hour     = $now->format('H');
    $nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
    if ($nminutes > $cminutes) {
        $nminutes -= 5;
    }
    if ($nminutes === 60) {
        $nminutes = 0;
        $hour++;
    }
    if ($hour === 24) {
        $hour = 0;
    }
    return sprintf('%02d:%02d', $hour, $nminutes);
}

echo secondsToTime();

演示


推荐阅读