PHP round the time to the nearest 15 seconds

2020-04-10 01:44发布

问题:

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:

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. also since I'm dealing with secs, it could be that 59:59 will be rounded up to the nearest hour: e.g. 17:59:59 should be 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

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)

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

Please and thank you in advance....

回答1:

You're massively overcomplicating this, just do rounding on the Unix timestamp level:

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.



回答2:

$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


回答3:

Convert the date to seconds using strtotime and then just work in seconds.

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