萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 相對時間格式化:「幾分鐘前、幾小時前、幾天前」多種實現與最佳實踐

需求背景

社交動態、評論列表、消息通知等場景需將絕對時間 (2024-01-15 14:30:00) 轉為相對時間 (「3分鐘前」、「2小時前」、「昨天」),提升用戶體驗。

方案一:分級判斷函數 (直觀、可控)

/**
 * 相對時間格式化 v1:分級閾值判斷
 * @param string|int $datetime 日期時間字符串或時間戳
 * @param int        $now      當前時間戳 (默認 time())
 * @return string 相對時間字符串
 */
function timeAgo($datetime, int $now = 0): string
{
    $now = $now ?: time();
    $ts = is_numeric($datetime) ? (int)$datetime : strtotime($datetime);
    if ($ts === false || $ts > $now) return date('Y-m-d H:i', $ts); // 未來/無效時間回退絕對格式
    
    $diff = $now - $ts;
    
    if ($diff < 60) {
        return $diff . '秒前';
    }
    if ($diff < 3600) {
        return floor($diff / 60) . '分鐘前';
    }
    if ($diff < 86400) {
        return floor($diff / 3600) . '小時前';
    }
    if ($diff < 259200) { // 3 天內
        return floor($diff / 86400) . '天前';
    }
    // 超過 3 天顯示具體日期
    return date('Y-m-d', $ts);
}

方案二:單位陣列遍歷 (可擴展、易維護)

/**
 * 相對時間格式化 v2:單位陣列遍歷
 * 易於擴展年/月/週,邏輯集中
 */
function formatRelativeTime($datetime, int $now = 0): string
{
    $now = $now ?: time();
    $ts = is_numeric($datetime) ? (int)$datetime : strtotime($datetime);
    if ($ts === false || $ts > $now) return date('Y-m-d H:i', $ts);
    
    $diff = $now - $ts;
    
    $units = [
        31536000 => '年',   // 365*86400
        2592000  => '個月', // 30*86400
        604800   => '週',
        86400    => '天',
        3600     => '小時',
        60       => '分鐘',
        1        => '秒',
    ];
    
    foreach ($units as $seconds => $unit) {
        if ($diff >= $seconds) {
            $value = floor($diff / $seconds);
            return $value . $unit . '前';
        }
    }
    return '剛剛';
}

方案三:精細分級 (含「剛剛」、「昨天」、「前天」)

/**
 * 相對時間格式化 v3:產品級細節體驗
 * - <1分鐘: 「剛剛」
 * - 1-59分: 「X分鐘前」
 * - 1-23時: 「X小時前」
 * - 1天: 「昨天 HH:MM」
 * - 2天: 「前天 HH:MM」
 * - 3-6天: 「X天前」
 * - 7-30天: 「X週前」
 * - 30-365天: 「X個月前」
 * - >1年: 「X年前」
 */
function humanTime($datetime, int $now = 0): string
{
    $now = $now ?: time();
    $ts = is_numeric($datetime) ? (int)$datetime : strtotime($datetime);
    if ($ts === false) return '未知時間';
    
    $diff = $now - $ts;
    if ($diff < 0) return date('Y-m-d H:i', $ts); // 未來時間
    
    if ($diff < 60) return '剛剛';
    if ($diff < 3600) return floor($diff/60) . '分鐘前';
    if ($diff < 86400) return floor($diff/3600) . '小時前';
    
    // 同一天內 (按 00:00 劃分)
    $todayStart = strtotime(date('Y-m-d', $now));
    if ($ts >= $todayStart) {
        return '今天 ' . date('H:i', $ts);
    }
    
    $yesterdayStart = $todayStart - 86400;
    if ($ts >= $yesterdayStart) {
        return '昨天 ' . date('H:i', $ts);
    }
    
    $dayBeforeYesterdayStart = $yesterdayStart - 86400;
    if ($ts >= $dayBeforeYesterdayStart) {
        return '前天 ' . date('H:i', $ts);
    }
    
    if ($diff < 604800) return floor($diff/86400) . '天前';
    if ($diff < 2592000) return floor($diff/604800) . '週前';
    if ($diff < 31536000) return floor($diff/2592000) . '個月前';
    
    return floor($diff/31536000) . '年前';
}

方案四:面向對象封裝 (可測試、可擴展、支援多語言)

/**
 * 相對時間格式化器
 * 支援:多語言、自定義閾值、時區、測試時鍵注入
 */
class RelativeTimeFormatter
{
    private array $thresholds; // [秒數 => [單位, 格式化器]]
    private DateTimeZone $tz;
    private ?int $fixedNow; // 測試用固定時間

    public function __construct(?DateTimeZone $tz = null)
    {
        $this->tz = $tz ?? new DateTimeZone(date_default_timezone_get());
        $this->thresholds = [
            60       => ['second', fn($v) => $v . '秒前'],
            3600     => ['minute', fn($v) => $v . '分鐘前'],
            86400    => ['hour',   fn($v) => $v . '小時前'],
            604800   => ['day',    fn($v) => $v . '天前'],
            2592000  => ['week',   fn($v) => $v . '週前'],
            31536000 => ['month',  fn($v) => $v . '個月前'],
            PHP_INT_MAX => ['year', fn($v) => $v . '年前'],
        ];
    }

    /** 設置固定「當前時間」用於單元測試 */
    public function setFixedNow(int $timestamp): self
    {
        $this->fixedNow = $timestamp;
        return $this;
    }

    public function format(string|int|DateTimeInterface $datetime): string
    {
        $now = $this->fixedNow ?? time();
        $ts = $this->toTimestamp($datetime);
        if ($ts === false || $ts > $now) {
            return $this->formatAbsolute($ts);
        }
        
        $diff = $now - $ts;
        if ($diff < 10) return '剛剛'; // 10秒內視為剛剛
        
        foreach ($this->thresholds as $seconds => [$unit, $formatter]) {
            if ($diff < $seconds) {
                $value = max(1, floor($diff / ($seconds / ($this->getUnitBase($unit)))));
                return $formatter($value);
            }
        }
        return $this->formatAbsolute($ts);
    }

    private function toTimestamp($datetime): int|false
    {
        if (is_int($datetime)) return $datetime;
        if ($datetime instanceof DateTimeInterface) return $datetime->getTimestamp();
        return strtotime($datetime);
    }

    private function getUnitBase(string $unit): int
    {
        return match ($unit) {
            'second' => 1,
            'minute' => 60,
            'hour'   => 3600,
            'day'    => 86400,
            'week'   => 604800,
            'month'  => 2592000,
            'year'   => 31536000,
            default  => 1,
        };
    }

    private function formatAbsolute(int $ts): string
    {
        $dt = new DateTime('@' . $ts);
        $dt->setTimezone($this->tz);
        return $dt->format('Y-m-d H:i');
    }
}

// 使用
$formatter = new RelativeTimeFormatter(new DateTimeZone('Asia/Shanghai'));
echo $formatter->format('2024-01-15 10:30:00'); // 3小時前
echo $formatter->setFixedNow(strtotime('2024-01-15 12:00:00'))->format('2024-01-15 10:30:00'); // 測試:1小時前

前端配合:時間戳本地化 (最佳實踐)

**後端只返回 ISO 8601 時間戳**,前端用 JS 實時計算相對時間,優勢:

  • 無時區困擾 (用戶本地時區)
  • 無需輪詢刷新,「剛剛」→「1分鐘前」自動更新
  • 減輕後端渲染壓力
<!-- 後端輸出 -->
<time datetime="2024-01-15T10:30:00+08:00" class="relative-time">2024-01-15 10:30</time>

<!-- 前端 JS (原生/輕量) -->

時區陷阱與對策

問題原因解決
時間差 8 小時PHP 默認 UTC,業務用北京時間php.ini date.timezone = Asia/Shanghai 或代碼 date_default_timezone_set('Asia/Shanghai')
跨天計算錯用 86400 秒判斷「天」忽略夏令時/閏秒用 DateTime::diff() 或按 00:00 劃分自然天
數據庫存儲不一致MySQL DATETIME 無時區,TIMESTAMP 自動轉換統一存 UTC (TIMESTAMP 或 DATETIME+應用層轉換),讀取時轉目標時區

性能優化

  • 高頻調用場景:緩存格式化結果 (Redis key: rel_time:{timestamp}:{lang},TTL 60s)
  • 批量渲染:前端 JS 統一處理,後端只輸出時間戳
  • 避免在循環中重複 date_default_timezone_set

總結

推薦**方案三 (產品級細節)** 用於服務端渲染頁面;**前端 JS 方案** 用於 SPA/實時流場景。面向對象封裝 (方案四) 適合大型項目,支援單元測試、多語言、時區隔離。核心原則:**業務邏輯存 UTC 時間戳,展示層按用戶上下文格式化**。

copyright © 萬盛學電腦網 all rights reserved