Home > Article > Backend Development > How to Round a Timestamp Down to the Nearest Quarter Hour in PHP?
Round Time Down to the Nearest Quarter Hour
Many applications require manipulating timestamps and performing calculations based on time. A common requirement is rounding a time to the nearest quarter hour. PHP provides several functions that can help with this task.
Here's a PHP script that demonstrates how to round a MySQL datetime field down to the nearest quarter hour:
<?php // Get the current datetime from the database $datetime = '2010-03-18 10:50:00'; // Convert the datetime into seconds $seconds = strtotime($datetime); // Calculate the number of seconds in 15 minutes $quarter_hour_seconds = 15 * 60; // Round the time down to the nearest quarter hour using floor() $rounded_seconds = floor($seconds / $quarter_hour_seconds) * $quarter_hour_seconds; // Convert the rounded time seconds into a datetime string $rounded_datetime = date('Y-m-d H:i:s', $rounded_seconds); echo "Original: $datetime\n"; echo "Rounded: $rounded_datetime\n"; ?>
The above is the detailed content of How to Round a Timestamp Down to the Nearest Quarter Hour in PHP?. For more information, please follow other related articles on the PHP Chinese website!