首頁 後端開發 php教程 如何在 PHP 中計算和格式化自某個日期以來經過的時間?

如何在 PHP 中計算和格式化自某個日期以來經過的時間?

Dec 16, 2024 pm 03:04 PM

How to Calculate and Format Elapsed Time Since a Date in PHP?

在PHP 中查找自日期時間以來經過的時間

確定自特定日期和時間以來經過的時間在各種應用程序中非常有用,例如顯示事件發生以來的時間。在 PHP 中,有多種方法可以以使用者友好的方式計算和格式化經過的時間。

計算經過的時間

計算給定日期之間經過的時間time 和當前時間,您可以使用strtotime() 函數將日期時間的字串表示形式轉換為時間戳。然後可以從當前時間戳中減去時間戳,當前時間戳表示自 Unix 紀元(1970 年 1 月 1 日 UTC)以來的當前時間(以秒為單位)。

例如:

$time = strtotime('2010-04-28 17:25:43');
$elapsedTime = time() - $time;

格式化經過時間

將經過時間作為數字後秒,您可以以用戶友好的方式格式化它。常見的方法是將秒數轉換為分鐘、天或年等單位。您可以使用循環迭代單位清單及其對應的秒數,然後傳回適當的單位及其值。

例如,以下函數計算並格式化經過的時間:

function humanTiming($time) {
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }
}

用法範例

要使用此函數,您只需將時間戳記作為參數:

$time = strtotime('2010-04-28 17:25:43');
echo 'Event happened '.humanTiming($time).' ago';

這將以適合用戶顯示的格式輸出經過的時間,例如「事件發生在4 天前」或「事件發生在 1 分鐘前」。

以上是如何在 PHP 中計算和格式化自某個日期以來經過的時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何使用PHP中的陣列 如何使用PHP中的陣列 Aug 20, 2025 pm 07:01 PM

phparrayshandledatAcollectionsefefityIndexedorassociativuctures; hearecreatedWithArray()或[],訪問decessedviakeys,modifybyAssignment,iteratifybyAssign,iteratedwithforeach,andManipulationUsfunsionsFunctionsLikeCountLikeCountLikeCountLikeCountLikecount()

描述觀察者的設計模式及其在PHP中的實現。 描述觀察者的設計模式及其在PHP中的實現。 Aug 15, 2025 pm 01:54 PM

TheObserverdesignpatternenablesautomaticnotificationofdependentobjectswhenasubject'sstatechanges.1)Itdefinesaone-to-manydependencybetweenobjects;2)Thesubjectmaintainsalistofobserversandnotifiesthemviaacommoninterface;3)Observersimplementanupdatemetho

如何在php中使用$ _cookie變量 如何在php中使用$ _cookie變量 Aug 20, 2025 pm 07:00 PM

$_COOKIEisaPHPsuperglobalforaccessingcookiessentbythebrowser;cookiesaresetusingsetcookie()beforeoutput,readvia$_COOKIE['name'],updatedbyresendingwithnewvalues,anddeletedbysettinganexpiredtimestamp,withsecuritybestpracticesincludinghttponly,secureflag

比較和對比PHP特徵,抽像類別和界面與實際用例。 比較和對比PHP特徵,抽像類別和界面與實際用例。 Aug 11, 2025 pm 11:17 PM

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

為MySQL支持的PHP應用程序說明數據庫索引策略(例如B-Tree,全文)。 為MySQL支持的PHP應用程序說明數據庫索引策略(例如B-Tree,全文)。 Aug 13, 2025 pm 02:57 PM

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

PHP中有什麼公共,私人和保護 PHP中有什麼公共,私人和保護 Aug 24, 2025 am 03:29 AM

public成員可被任意訪問;2.private成員僅類內可訪問;3.protected成員可在類及子類中訪問;4.合理使用可提升代碼安全與可維護性。

如何在PHP中執行更新查詢 如何在PHP中執行更新查詢 Aug 24, 2025 am 05:04 AM

使用MySQLi面向對象方式:建立連接,預處理UPDATE語句,綁定參數,執行並檢查結果,最後關閉資源。 2.使用MySQLi過程方式:通過函數連接數據庫,準備語句,綁定參數,執行更新,處理錯誤後關閉連接。 3.使用PDO:通過PDO連接數據庫,設置異常模式,預處理SQL,綁定參數,執行更新,用try-catch處理異常,最後釋放資源。始終使用預處理語句防止SQL注入,驗證用戶輸入,及時關閉連接。

如何與PHP中的日期和時間一起工作 如何與PHP中的日期和時間一起工作 Aug 20, 2025 pm 06:57 PM

UnedateTimeFordateSinphp:createWithNewDateTime(),formatwithformat(),modifyviaadd()ormodify(),settimezoneswithdateTimeZone,and compareusingoperatorSordiff()togetIntervals。

See all articles