首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實現「幾分鐘前」「幾天前」等相對時間顯示函數

     編輯:PHP 綜合知識

算法邏輯

計算給定時間與當前時間的秒數差,按閾值分級:<60秒→秒,<3600→分鐘,<86400→小時,<2629743.83(30.4375天)→天,<31556926(365.25天)→月,其它→年。單複數自動判斷。

代碼實現

function prettyDate($date) {
    $time = strtotime($date);
    $now = time();
    $ago = $now - $time;
    if ($ago < 60) {
        $when = round($ago);
        $s = ($when == 1) ? "second" : "seconds";
        return "$when $s ago";
    } elseif ($ago < 3600) {
        $when = round($ago / 60);
        $m = ($when == 1) ? "minute" : "minutes";
        return "$when $m ago";
    } elseif ($ago < 86400) {
        $when = round($ago / 3600);
        $h = ($when == 1) ? "hour" : "hours";
        return "$when $h ago";
    } elseif ($ago < 2629743.83) {
        $when = round($ago / 86400);
        $d = ($when == 1) ? "day" : "days";
        return "$when $d ago";
    } elseif ($ago < 31556926) {
        $when = round($ago / 2629743.83);
        $m = ($when == 1) ? "month" : "months";
        return "$when $m ago";
    } else {
        $when = round($ago / 31556926);
        $y = ($when == 1) ? "year" : "years";
        return "$when $y ago";
    }
}

// 測試
echo prettyDate("2012-07-22 12:23:45") . "<br />";
echo prettyDate("2010-11-12 22:25:45") . "<br />";
echo prettyDate("2012-01-01 01:00:00") . "<br />";
echo prettyDate("2001-05-30 00:00:00") . "<br />";

輸出示例(假設當前 2015-02-11)

2 days ago
4 years ago
3 years ago
14 years ago

中文化擴展

function prettyDateCN($date) {
    $ago = time() - strtotime($date);
    $units = [
        31556926 => '年',
        2629743.83 => '個月',
        86400 => '天',
        3600 => '小時',
        60 => '分鐘',
        1 => '秒',
    ];
    foreach ($units as $sec => $unit) {
        if ($ago >= $sec) {
            $val = floor($ago / $sec);
            return "$val$unit前";
        }
    }
    return "剛剛";
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved