萬盛學電腦網

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

PHP 相對時間格式化:「3天前、5分鐘前、2年前」人性化顯示

核心函數

<?php
/**
 * 將日期時間轉為相對時間字串
 * @param string|int|DateTime $datetime 目標時間
 * @param string $lang 語言:zh/en,預設 zh
 * @return string 如「3天前」「5分鐘前」「2年前」
 */
function timeAgo($datetime, string $lang = 'zh'): string
{
    $now = time();
    $target = $datetime instanceof DateTimeInterface
        ? $datetime->getTimestamp()
        : (is_numeric($datetime) ? (int)$datetime : strtotime($datetime));

    if ($target > $now) $target = $now; // 未來時間視為剛剛

    $diff = $now - $target;

    $units = $lang === 'zh' 
        ? ['年' => 31556926, '個月' => 2629744, '周' => 604800, '天' => 86400, '小時' => 3600, '分鐘' => 60, '秒' => 1]
        : ['year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1];

    foreach ($units as $unit => $seconds) {
        if ($diff >= $seconds) {
            $value = (int)($diff / $seconds);
            return $lang === 'zh' 
                ? "{$value}{$unit}前" 
                : "{$value} {$unit}" . ($value > 1 ? 's' : '') . " ago";
        }
    }
    return $lang === 'zh' ? '剛剛' : 'just now';
}
?>

使用範例

<?php
echo timeAgo('2024-01-10 12:00:00');      // 5天前 (假設今天 2024-01-15)
echo timeAgo(strtotime('-2 hours'));      // 2小時前
echo timeAgo(time() - 30);                // 30秒前
echo timeAgo('2023-01-01');               // 1年前
echo timeAgo('2024-01-15 10:00', 'en');   // 2 hours ago
?>

進階版:支援「未來時間」、「剛剛」閾值、完整日期回退

<?php
function timeAgoAdvanced($datetime, array $options = []): string
{
    $opts = array_merge([
        'lang' => 'zh',
        'justNowThreshold' => 30,      // 幾秒內算「剛剛」
        'futureText' => 'zh' => '未來時間', 'en' => 'in the future',
        'fallbackFormat' => 'Y-m-d H:i', // 超過年份顯示完整日期
    ], $options);

    $now = time();
    $target = $datetime instanceof DateTimeInterface
        ? $datetime->getTimestamp()
        : (is_numeric($datetime) ? (int)$datetime : strtotime($datetime));

    if ($target > $now) {
        return $opts['futureText'][$opts['lang']] ?? $opts['futureText'];
    }

    $diff = $now - $target;

    if ($diff < $opts['justNowThreshold']) {
        return $opts['lang'] === 'zh' ? '剛剛' : 'just now';
    }

    $units = $opts['lang'] === 'zh'
        ? [['年', 31556926], ['個月', 2629744], ['周', 604800], ['天', 86400], ['小時', 3600], ['分鐘', 60], ['秒', 1]]
        : [['year', 31556926], ['month', 2629744], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];

    foreach ($units as [$unit, $seconds]) {
        if ($diff >= $seconds) {
            $value = (int)($diff / $seconds);
            if ($opts['lang'] === 'zh') {
                return "{$value}{$unit}前";
            }
            return "{$value} {$unit}" . ($value > 1 ? 's' : '') . " ago";
        }
    }

    // 理論上不會到這裡,但保險起見
    return date($opts['fallbackFormat'], $target);
}
?>

Laravel / Carbon 風格擴充

<?php
// 如果專案用 Carbon,直接用內建
use Carbon\Carbon;

$dt = Carbon::parse('2024-01-10 12:00:00');
echo $dt->diffForHumans();           // 5 days ago
echo $dt->locale('zh_TW')->diffForHumans(); // 5 天前

// 自訂閾值
echo $dt->diffForHumans(['short' => true]); // 5d ago
?>

前端 JavaScript 版(配合後端統一格式)

<script>
function timeAgo(timestamp, lang = 'zh') {
    const now = Date.now() / 1000;
    const diff = now - timestamp;
    if (diff < 30) return lang === 'zh' ? '剛剛' : 'just now';
    
    const units = lang === 'zh'
        ? [['年', 31556926], ['個月', 2629744], ['周', 604800], ['天', 86400], ['小時', 3600], ['分鐘', 60], ['秒', 1]]
        : [['year', 31556926], ['month', 2629744], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
    
    for (const [unit, seconds] of units) {
        if (diff >= seconds) {
            const value = Math.floor(diff / seconds);
            return lang === 'zh' ? `${value}${unit}前` : `${value} ${unit}${value > 1 ? 's' : ''} ago`;
        }
    }
    return new Date(timestamp * 1000).toLocaleDateString();
}

// 使用:後端輸出 Unix timestamp
// <span data-time="created_at->timestamp ?>"></span>
document.querySelectorAll('[data-time]').forEach(el => {
    el.textContent = timeAgo(el.dataset.time);
});
</script>

效能優化:快取格式化結果

<?php
function timeAgoCached($datetime, string $lang = 'zh'): string
{
    static $cache = [];
    $key = ($datetime instanceof DateTimeInterface ? $datetime->getTimestamp() : (int)$datetime) . '|' . $lang;
    
    if (!isset($cache[$key])) {
        $cache[$key] = timeAgo($datetime, $lang);
    }
    return $cache[$key];
}

// 模板中大量使用時極大提升效能
foreach ($articles as $article) {
    echo '';
}
?>

國際化(i18n)擴充建議

<?php
// 使用 PHP 內建 NumberFormatter + 自訂規則
$fmt = new NumberFormatter('zh_TW', NumberFormatter::SPELLOUT);
// 但相對時間建議自行維護翻譯檔,更靈活

// 翻譯檔結構建議:
return [
    'zh_TW' => [
        'just_now' => '剛剛',
        'seconds_ago' => '{count}秒前',
        'minutes_ago' => '{count}分鐘前',
        'hours_ago' => '{count}小時前',
        'days_ago' => '{count}天前',
        'weeks_ago' => '{count}週前',
        'months_ago' => '{count}個月前',
        'years_ago' => '{count}年前',
    ],
    'en_US' => [
        'just_now' => 'just now',
        'seconds_ago' => '{count} second{plural} ago',
        // ...
    ],
];
?>

相對時間格式化是提升使用者體驗的小細節,幾行程式碼即可實現,建議封裝為工具函數專案通用。

copyright © 萬盛學電腦網 all rights reserved