Home  >  Article  >  Backend Development  >  How to Round a Timestamp Down to the Nearest Quarter Hour in PHP?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 20:28:01320browse

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!

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