I am using the following function to round the time to closest 15 minutes.
function roundTime($time){
$seconds = $time;
$rounded_seconds = round($seconds / (15 * 60)) * (15 * 60);
return date('H:i', $rounded_seconds) . "n";
}
What I actually need it to be able to round UP or round DOWN to closest 15 minutes, OR 30 minutes of my choice. Separate functions can be used for each.
After searching for rounding up/down, I am aware of the functions floor and ceil but I can’t understand how to use them with time?
For example, if I have the time of 14:05, I would like to be able to round it up to closes 15 min, for example 14:15, and to round up to closes 30 min, 14:30 I want to be able to decide weather to round up or down.
Instead of rounding to closest 15 min, I want to be able to round UP or round DOWN to closes 15 min, if that makes sense.
The code is used for clocking system. The employee needs to have full 15 minutes in order for it to count as overtime. For example, if they clock out at 14:26, they get paid until 14:15.
2
Answers
You would have to add two parameters to your function: The wanted interval, 15 or 30 minutes, and whether you want to round down or up. Something like this:
Live demo: https://3v4l.org/g75tA
It is very similar to the function you had apart from some optimizations.
If you want something fully flexible where you can choose the rounding interval and the direction, you can pass these options in as arguments to the function, perhaps like this:
This test data will output:
Live demo: https://3v4l.org/oqOTE