Home > Article > Backend Development > How to Round Down Minutes to the Nearest Quarter Hour in PHP?
Round Minute Down to Nearest Quarter Hour in PHP
Rounding times down to the nearest quarter hour in PHP is a common task. This article explores a solution using the floor() function, addressing the specific query:
$time = '10:50:00'; // Example time in datetime format $rounded_time = roundMinuteDownToNearestQuarter($time);
Solution
To round a minute down to the nearest quarter hour, we need to:
Here's the code:
function roundMinuteDownToNearestQuarter($time) { // Convert the time string to a timestamp $timestamp = strtotime($time); // Divide by 15 minutes (900 seconds) and round down $rounded_timestamp = floor($timestamp / 900) * 900; // Convert the rounded timestamp back to a time string return date('H:i', $rounded_timestamp); }
Example
$time = '10:50:00'; $rounded_time = roundMinuteDownToNearestQuarter($time); echo "Original: " . $time . "\n"; echo "Rounded down: " . $rounded_time . "\n";
Output:
Original: 10:50:00 Rounded down: 10:45:00
The above is the detailed content of How to Round Down Minutes to the Nearest Quarter Hour in PHP?. For more information, please follow other related articles on the PHP Chinese website!