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

DDD
Release: 2024-11-09 20:49:02
Original
933 people have browsed it

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

Rounding Minutes to the Nearest Quarter Hour in PHP

Consider the need to round times down to the nearest quarter hour from a MySQL database, where the times are formatted as datetime values (e.g., 2010-03-18 10:50:00). The goal is to achieve the following rounding conversions:

  • 10:50 to 10:45
  • 1:12 to 1:00
  • 3:28 to 3:15

To accomplish this task, we can utilize the floor() function in PHP. The following steps outline the approach:

  1. Convert the datetime timestamp into a timestamp in seconds using the strtotime() function.
  2. Determine the time in seconds rounded down to the nearest quarter hour using floor() and the appropriate conversion factor (15 minutes into seconds).
  3. Convert the rounded seconds back into a datetime format using the date() function.

Here's an example to illustrate the process:

<?php
// Get the current time and convert it to a timestamp in seconds
$seconds = time();

// Round the timestamp to the nearest quarter hour using floor()
$rounded_seconds = floor($seconds / (15 * 60)) * (15 * 60);

// Convert the rounded seconds back to a datetime format
$original_time = date('h:i', $seconds);
$rounded_time = date('h:i', $rounded_seconds);

// Print the original and rounded times
echo "Original: $original_time" . PHP_EOL;
echo "Rounded: $rounded_time" . PHP_EOL;
?>
Copy after login

Note: If you want to round the time up to the nearest quarter hour instead of down, replace floor() with ceil().

The above is the detailed content of How to Round 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template