PHP将时间四舍五入到最接近的15秒


PHP round the time to the nearest 15 seconds

这不是一个重复的问题,但需要对时间有一点了解。

我需要以下问题的解决方案我有一些特定生成的时间(基于日期),需要四舍五入到最接近的15秒:

60秒是1分钟表示规则的圆形、地板、天花板,精确到小数点后(10/5)这对我的时间没有帮助。同样,由于我处理的是秒,59:59可能会四舍五入到最接近的小时:例如,17:59:59应该是18:00。

示例:

6:17:29四舍五入至6:17:306:29:55四舍五入至6:30:0020: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:8,这也是不正确的

请提前表示感谢。。。。

您对这一点过于复杂了,只需在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

在这里演示。

$seconds = ($hr * 60 + $mn) * 60 + $sc; // convert to seconds
$rounded = round($seconds/15)*15;       // round
$sc = $rounded % 60;                    // get seconds
$mn = ($rounded - $sc) / 60 % 60;       // get minutes
$hr = ($rounded - $sc - $mn * 60) / 60; // get hours

使用strtotime将日期转换为秒,然后以秒为单位工作。

$seconds = strtotime($date);
$seconds /= 15;
$seconds = round($seconds);
$seconds *= 15;
$date = date("Y-m-d H:i:s", $seconds);