这不是一个重复的问题,但涉及到对时间的一点理解。
我需要解决以下问题 我有一些专门制作的时间(基于日期),需要四舍五入到最接近的 15 秒:
60 秒是 1 分钟 表示常规回合、下限、上限是最接近的小数点 (10/5) 这对我没有时间帮助。 也因为我正在处理 secs,所以 59:59 可能会四舍五入到最近的小时:例如17:59:59 应该是 18:00。
例子:
6:17:29 四舍五入为 6:17:30 6:29:55 四舍五入为 6:30:00 20:45:34 四舍五入为 20:45:30
下面的代码完成了一些工作:
$hr = date('H',($resultStr));
$mn = date('i',($resultStr));
$sc = date('s',($resultStr));
$tot = ($hr * 60 * 60) + ($mn * 60) + $sc;
$totd = $tot / (60);
$totc = ceil($totd);
$totc = $totc / 60;
$hr = floor($totc);
$mn = ($totc - $hr)*60;
$mnflr = floor($mn);
$mn2 = $mn - $mnflr;
echo "$hr:$mnflr";
这导致: 18:35:17 四舍五入为:18:36(这是错误的) 18:31:49 四舍五入为:18:32(这是错误的)
顺便说一句:
$secs = date('U',($resultStr));
$round = ceil ( (($secs / 60 ) * 60 ));
$newtime = date('H:i:s',($round));
产生:18:42:58 四舍五入为:18:42:58 这也是不正确的
请提前谢谢你....
最佳答案
你把这个复杂化了很多,只是在 Unix 时间戳级别上进行舍入:
function roundMyTime($time)
{
$time = strtotime($time);
$time = 15*round($time/15);
echo date('H:i:s', $time)."\n";
}
roundMyTime('18:35:17');
roundMyTime('18:35:27');
roundMyTime('18:35:37');
roundMyTime('18:35:47');
roundMyTime('18:35:57');
roundMyTime('18:36:07');
roundMyTime('18:36:17');
输出:
18:35:15
18:35:30
18:35:30
18:35:45
18:36:00
18:36:00
18:36:15
关于PHP 将时间四舍五入到最接近的 15 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26414766/