Home  >  Article  >  Backend Development  >  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
Mary-Kate OlsenOriginal
2024-11-07 21:38:02503browse

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:

  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);
}

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!

Statement:
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