首頁 > 後端開發 > php教程 > 如何在 PHP 中將時間戳向下舍入到最近的刻鐘?

如何在 PHP 中將時間戳向下舍入到最近的刻鐘?

Linda Hamilton
發布: 2024-11-08 20:28:01
原創
440 人瀏覽過

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

將時間向下舍入到最近的刻鐘

許多應用程式需要操作時間戳並根據時間執行計算。一個常見的要求是將時間四捨五入到最接近的一刻鐘。 PHP 提供了幾個可以幫助完成此任務的函數。

以下 PHP 腳本示範如何將 MySQL 日期時間欄位四捨五入到最近的一刻鐘:

<?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";

?>
登入後複製

以上是如何在 PHP 中將時間戳向下舍入到最近的刻鐘?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板