Round Minute Down to Nearest Quarter Hour in PHP
To round the time stored in a MySQL 'datetime' column down to the nearest quarter hour, we can leverage the 'floor()' function.
$sql = "SELECT datetime_column FROM table_name"; $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result)) { $timestamp = strtotime($row['datetime_column']); $rounded_time = floor($timestamp / (15 * 60)) * (15 * 60); // Convert the rounded timestamp back to a time string $rounded_time_string = date('H:i', $rounded_time); }
In this example:
Example:
$timestamp = strtotime('2010-03-18 10:50:00'); $rounded_time = floor($timestamp / (15 * 60)) * (15 * 60); echo date('H:i', $rounded_time); // Output: 10:45
Note that this approach can also be used to round up to the nearest quarter by replacing 'floor()' with 'ceil()'.
The above is the detailed content of How to Round a DateTime Down to the Nearest Quarter Hour in PHP?. For more information, please follow other related articles on the PHP Chinese website!