Home > Backend Development > PHP Tutorial > How to Round Down Minutes to the Nearest Quarter Hour in PHP?

How to Round Down Minutes to the Nearest Quarter Hour in PHP?

Mary-Kate Olsen
Release: 2024-11-07 21:38:02
Original
535 people have browsed it

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

Solution

To round a minute down to the nearest quarter hour, we need to:

  1. Convert the time string to a timestamp using strtotime() or DateTime().
  2. Divide the timestamp by 15 minutes (900 seconds) and round it down using floor().
  3. Multiply the rounded value by 15 minutes to get the timestamp of the nearest quarter hour.
  4. Convert the timestamp back to a time string using date().

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

Example

$time = '10:50:00';
$rounded_time = roundMinuteDownToNearestQuarter($time);
echo "Original: " . $time . "\n";
echo "Rounded down: " . $rounded_time . "\n";
Copy after login

Output:

Original: 10:50:00
Rounded down: 10:45:00
Copy after login

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!

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