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....
Convert the date to seconds using
strtotime
and then just work in seconds.You're massively overcomplicating this, just do rounding on the Unix timestamp level:
Outputs:
Demo here.