简体   繁体   English

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

[英]PHP round the time to the nearest 15 seconds

This is not a duplicate question, but involves a little understanding about time.这不是一个重复的问题,而是涉及对时间的一些了解。

I need a solution to the following problem I have a number of specifically produced times (based on a date), that need to be rounded to the nearest 15 secs:我需要解决以下问题我有许多专门生成的时间(基于日期),需要四舍五入到最接近的 15 秒:

60 secs is 1 minute meaning a regular round, floor, ceiling is to the nearest decimal (10/5) which doesn't help me with time. 60 秒是 1 分钟,这意味着常规的圆形、地板、天花板是最接近的小数 (10/5),这对我的时间没有帮助。 also since I'm dealing with secs, it could be that 59:59 will be rounded up to the nearest hour: eg 17:59:59 should be 18:00.此外,由于我正在处理秒,因此 59:59 可能会四舍五入到最接近的小时:例如 17:59:59 应该是 18:00。

example:例子:

6:17:29 rounded to 6:17:30 6:29:55 rounded to 6:30:00 20:45:34 rounded to 20:45:30 6:17:29 舍入到 6:17:30 6:29:55 舍入到 6:30:00 20:45:34 舍入到 20:45:30

The following code does some of the job:以下代码完成了一些工作:

$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";

This results in: 18:35:17 rounded to: 18:36 (which is wrong) 18:31:49 rounded to: 18:32 (which is wrong)这导致: 18:35:17 四舍五入到: 18:36 (这是错误的) 18:31:49 四舍五入到: 18:32 (这是错误的)

As an aside:作为旁白:

$secs = date('U',($resultStr));
$round = ceil ( (($secs / 60 ) * 60 ));
$newtime = date('H:i:s',($round));

produces: 18:42:58 rounded to: 18:42:58 which is also incorrect产生: 18:42:58 四舍五入为: 18:42:58 这也是不正确的

Please and thank you in advance....请提前谢谢你......

You're massively overcomplicating this, just do rounding on the Unix timestamp level:你把这个问题复杂化了,只需在 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');

Outputs:输出:

18:35:15
18:35:30
18:35:30
18:35:45
18:36:00
18:36:00
18:36:15

Demo here .演示在这里

$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

Convert the date to seconds using strtotime and then just work in seconds.使用strtotime将日期转换为秒,然后以秒为单位工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM