萬盛學電腦網

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

PHP 計算相對時間(幾秒前、幾分鐘前、幾天前)的通用函數

社交動態、評論列表、日誌時間軸常需展示「相對時間」(如「3分鐘前」、「2天前」)。本文提供一個健壯的 getRelativeTime() 函數,支援秒/分/時/天/週/月/年自動換算,含複數形式處理,並給出現代化替代方案。

基礎實現

function plural(int $n): string {
    return $n !== 1 ? 's' : '';
}

function getRelativeTime(string|DateTime $date): string {
    $ts = $date instanceof DateTime ? $date->getTimestamp() : strtotime($date);
    $diff = time() - $ts;

    if ($diff < 0) return '剛剛'; // 未來時間容錯

    if ($diff < 60)       return "$diff 秒" . plural($diff) . "前";
    $diff = round($diff / 60);
    if ($diff < 60)       return "$diff 分鐘" . plural($diff) . "前";
    $diff = round($diff / 60);
    if ($diff < 24)       return "$diff 小時" . plural($diff) . "前";
    $diff = round($diff / 24);
    if ($diff < 7)        return "$diff 天" . plural($diff) . "前";
    $diff = round($diff / 7);
    if ($diff < 4.3)      return "$diff 週" . plural($diff) . "前";
    $diff = round($diff / 4.34524);
    if ($diff < 12)       return "$diff 個月" . plural($diff) . "前";
    $diff = round($diff / 12);
    return "$diff 年" . plural($diff) . "前";
}

// 使用
echo getRelativeTime('2024-01-15 10:30:00'); // 例如 "3 天前"
echo getRelativeTime(new DateTime('-2 hours')); // "2 小時前"

進階增強版(支援本地化、閾值配置、未來時間)

function relativeTime(DateTimeInterface $date, array $options = []): string {
    $opts = array_merge([
        'locale' => 'zh_CN',
        'now' => new DateTimeImmutable(),
        'round' => true,
        'thresholds' => [60, 3600, 86400, 604800, 2629744, 31556926], // 秒/分/時/天/週/月/年
        'strings' => [
            'now' => '剛剛',
            'second' => '{count}秒前', 'minute' => '{count}分鐘前', 'hour' => '{count}小時前',
            'day' => '{count}天前', 'week' => '{count}週前', 'month' => '{count}個月前', 'year' => '{count}年前',
            'future' => '{count}秒後', // 同理擴展
        ],
    ], $options);

    $diff = $opts['now']->getTimestamp() - $date->getTimestamp();
    $sign = $diff < 0 ? 'future' : 'past';
    $diff = abs($diff);

    $units = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'];
    $unit = 'second';
    foreach ($opts['thresholds'] as $i => $threshold) {
        if ($diff < $threshold) { $unit = $units[$i]; break; }
        $diff = $opts['round'] ? round($diff / ($i===0?60:($i===1?60:($i===2?24:($i===3?7:($i===4?4.34524:12)))))) : $diff;
    }

    $template = $opts['strings'][$sign === 'past' ? $unit : 'future'];
    return str_replace('{count}', (string)$diff, $template);
}

現代最佳實踐:Carbon / nesbot/carbon

use Carbon\Carbon;
echo Carbon::parse('2024-01-15 10:30')->diffForHumans(); // "3 天前"
echo Carbon::parse('2024-01-15 10:30')->locale('zh_CN')->diffForHumans(['short' => true]); // "3天前"
echo Carbon::now()->addDays(2)->diffForHumans(); // "2 天后"
  • 內建 140+ 語言、相對/絕對、短格式、語法糖(->addDays()、->startOfWeek())。
  • Laravel、Symfony、Yii、ThinkPHP 等框架已集成或推薦 Carbon。
  • 原生 PHP 8.1+ 可用 DateTime::diff() + DateInterval::format() 手動構建,但 Carbon 體驗遠優。

邊界情況處理

  1. 時區一致性:存儲 UTC,展示時轉換為用戶時區(DateTimeZone)。
  2. 閏秒/夏令時:time() 返回 Unix 時間戳不受影響,但跨天界限需用 DateTime 運算。
  3. 極大時間差:年份換算用 365.2425 天更精確,或直接調用 DateInterval 的 y/m/d/h/i/s 屬性。
  4. 緩存:高頻顯示(如評論列表)可在寫入時預計算相對時間字符串存入 relative_time 字段,定期任務刷新。

相對時間函數是「寫一次、用到處」的典型工具函數,建議封裝到項目公共 helpers.php 或 Composer 包中統一維護。

copyright © 萬盛學電腦網 all rights reserved