Rounding Minutes to the Nearest Quarter Hour in PHP
Consider the need to round times down to the nearest quarter hour from a MySQL database, where the times are formatted as datetime values (e.g., 2010-03-18 10:50:00). The goal is to achieve the following rounding conversions:
To accomplish this task, we can utilize the floor() function in PHP. The following steps outline the approach:
Here's an example to illustrate the process:
<?php // Get the current time and convert it to a timestamp in seconds $seconds = time(); // Round the timestamp to the nearest quarter hour using floor() $rounded_seconds = floor($seconds / (15 * 60)) * (15 * 60); // Convert the rounded seconds back to a datetime format $original_time = date('h:i', $seconds); $rounded_time = date('h:i', $rounded_seconds); // Print the original and rounded times echo "Original: $original_time" . PHP_EOL; echo "Rounded: $rounded_time" . PHP_EOL; ?>
Note: If you want to round the time up to the nearest quarter hour instead of down, replace floor() with ceil().
The above is the detailed content of How to Round Minutes to the Nearest Quarter Hour in PHP?. For more information, please follow other related articles on the PHP Chinese website!