PHP up to next 15 seconds

This is not a duplicate question, but it does take a little time to understand.

I need a solution to the following problem I have a specific amount of time (based on a date) that needs to be rounded to the nearest 15 seconds:

60 seconds - 1 minute i.e. regular round, floor, ceiling to the nearest decimal (10/5) which doesn't help me with time. also, since I am dealing with secs, it may be that 59:59 will be rounded to the nearest hour: eg. 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 things:

$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)

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, thank you in advance.

+3


source to share


3 answers


You are breaking this badly, just do rounding at the Unix mark 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 is here .

+5


source


$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

      



0


source


Convert your date to seconds with strtotime

and then just in seconds.

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

      

0


source







All Articles