这不是一个重复的问题,但需要对时间有一点了解.
我需要解决以下问题
我有一些特定生产时间(基于日期),需要四舍五入到最接近的15秒:
60秒是1分钟
意思是一个常规的圆形,地板,天花板是到最接近的十进制(10/5)
这对时间没有帮助.
因为我正在处理秒,所以可能是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