php - 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 ...
解决方案
您需要对分钟进行四舍五入,然后重新格式化输出日期。
这里隐藏着一些陷阱。正如您最终可以得到 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();
推荐阅读
- python - 如何指定路径中不存在的文件?
- google-cloud-functions - 用于向令牌集合发送 fcm 通知的云功能
- amazon-ec2-spot-market - 暂时停止 Spot 实例
- mysql - Hive 表到 MySQL 表的转换
- nginx - 无法将 Browsersync 与 DDEV nginx 服务器连接,因为 SSL 错误
- swift - 字典中的随机元素
- mongodb - 如何将远程服务器中的 Mongo DB 连接到我的 Docker?
- sql - 如何在 Oracle APEX 交互式网格报表中维护正在运行的计数器
- c# - VSTO Outlook 插件开发
- git - 将更改合并到分支上,但不从目标分支中获取更改