萬盛學電腦網

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

PHP 相對時間顯示:幾秒前、幾分鐘前、幾小時前、日期格式化

需求場景

社群動態、評論、文章列表常需顯示「剛剛」、「5 分鐘前」、「3 小時前」、「昨天」、「2024-01-15」等相對時間。本文提供可直接使用的 timeAgo() 函數,支援自訂閾值、多語系、快取友善。

核心函數

<?php
/**
 * 格式化相對時間
 * @param int $timestamp Unix 時間戳
 * @param array $options 選項:
 *   - 'now' => 當前時間戳(預設 time())
 *   - 'locale' => 語系代碼(預設 'zh-Hant')
 *   - 'thresholds' => 閾值陣列 [秒, 分鐘, 小時, 天]
 * @return string
 */
function timeAgo(int $timestamp, array $options = []): string
{
    $now = $options['now'] ?? time();
    $locale = $options['locale'] ?? 'zh-Hant';
    $diff = $now - $timestamp;

    // 未來時間處理
    if ($diff < 0) {
        return match ($locale) {
            'zh-Hant', 'zh-CN' => '剛剛',
            'en' => 'just now',
            default => 'just now',
        };
    }

    // 閾值(秒)
    $minute = 60;
    $hour = 3600;
    $day = 86400;
    $week = 604800;
    $month = 2592000;
    $year = 31536000;

    if ($diff < $minute) {
        return match ($locale) {
            'zh-Hant', 'zh-CN' => '剛剛',
            'en' => 'just now',
            default => 'just now',
        };
    } elseif ($diff < $hour) {
        $mins = (int)($diff / $minute);
        return match ($locale) {
            'zh-Hant', 'zh-CN' => "{$mins} 分鐘前",
            'en' => $mins === 1 ? '1 minute ago' : "{$mins} minutes ago",
            default => "{$mins}m ago",
        };
    } elseif ($diff < $day) {
        $hours = (int)($diff / $hour);
        return match ($locale) {
            'zh-Hant', 'zh-CN' => "{$hours} 小時前",
            'en' => $hours === 1 ? '1 hour ago' : "{$hours} hours ago",
            default => "{$hours}h ago",
        };
    } elseif ($diff < $week) {
        $days = (int)($diff / $day);
        return match ($locale) {
            'zh-Hant', 'zh-CN' => $days === 1 ? '昨天' : "{$days} 天前",
            'en' => $days === 1 ? 'yesterday' : "{$days} days ago",
            default => "{$days}d ago",
        };
    } elseif ($diff < $month) {
        $weeks = (int)($diff / $week);
        return match ($locale) {
            'zh-Hant', 'zh-CN' => "{$weeks} 週前",
            'en' => $weeks === 1 ? '1 week ago' : "{$weeks} weeks ago",
            default => "{$weeks}w ago",
        };
    } elseif ($diff < $year) {
        $months = (int)($diff / $month);
        return match ($locale) {
            'zh-Hant', 'zh-CN' => "{$months} 個月前",
            'en' => $months === 1 ? '1 month ago' : "{$months} months ago",
            default => "{$months}mo ago",
        };
    } else {
        $years = (int)($diff / $year);
        return match ($locale) {
            'zh-Hant', 'zh-CN' => "{$years} 年前",
            'en' => $years === 1 ? '1 year ago' : "{$years} years ago",
            default => "{$years}y ago",
        };
    }
}
?>

進階:輸出完整日期(超過閾值)

<?php
function timeAgoWithDate(int $timestamp, array $options = []): string
{
    $now = $options['now'] ?? time();
    $diff = $now - $timestamp;
    $locale = $options['locale'] ?? 'zh-Hant';
    $dateFormat = $options['date_format'] ?? 'Y-m-d H:i';

    // 24 小時內顯示相對時間
    if ($diff < 86400) {
        return timeAgo($timestamp, $options);
    }

    // 超過 24 小時顯示完整日期(可選擇時區)
    $tz = $options['timezone'] ?? date_default_timezone_get();
    $dt = new DateTime("@$timestamp");
    $dt->setTimezone(new DateTimeZone($tz));
    return $dt->format($dateFormat);
}

// 使用
echo timeAgoWithDate(strtotime('-2 hours'));     // 2 小時前
echo timeAgoWithDate(strtotime('-3 days'));      // 2024-01-15 14:30
echo timeAgoWithDate(strtotime('+1 hour'));      // 剛剛(未來時間)
?>

前端最佳實務:timeago.js / 相對時間元件

後端僅輸出 ISO 8601 時間戳(<time datetime="2024-01-15T14:30:00+08:00">),前端用 JavaScript 計算相對時間,優點:

  • ✅ 零時區問題(瀏覽器自動處理)
  • ✅ 自動即時更新(每分鐘重算)
  • ✅ 多語系切換無需後端支援
  • ✅ 可快取 HTML(時間邏輯在前端)
<!-- HTML -->
<time class="timeago" datetime="2024-01-15T14:30:00+08:00">2024-01-15 14:30</time>

<!-- JS (使用 timeago.js 或原生 Intl.RelativeTimeFormat) -->
<script>
document.querySelectorAll('time.timeago').forEach(el => {
    const dt = new Date(el.dateTime);
    const rtf = new Intl.RelativeTimeFormat(navigator.language, { numeric: 'auto' });
    const diff = (dt - Date.now()) / 1000; // 秒
    // 簡易邏輯...
    el.textContent = rtf.format(Math.round(diff/60), 'minute');
});
</script>

資料庫層面優化

  • 儲存 TIMESTAMP 或 DATETIME(UTC),不儲存相對時間字串
  • 查詢時直接 SELECT UNIX_TIMESTAMP(created_at) AS ts 或在 PHP 端 strtotime()
  • 列表頁避免逐筆呼叫 timeAgo(),改用前端渲染或批次處理

總結

timeAgo() 為後端快速產生相對時間字串的實用工具,但現代前端架構建議改由前端處理(輸出 ISO 8601 + <time> 標籤)。若必須後端渲染,請善用快取、避免重複計算,並提供多語系、時區選項。

copyright © 萬盛學電腦網 all rights reserved