How to Round a DateTime Down to the Nearest Quarter Hour in PHP?

Susan Sarandon
Release: 2024-11-08 10:19:02
Original
193 people have browsed it

How to Round a DateTime Down to the Nearest Quarter Hour in PHP?

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);
}
Copy after login

In this example:

  • The 'floor()' function is used to round the timestamp down to the nearest quarter.
  • The timestamp is divided by "(15 * 60)" to convert it to minutes, then multiplied by the same value to round it back to the nearest quarter.
  • Finally, the rounded timestamp is converted back to a time string using 'date()'.

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template