社交動態、評論列表、日誌時間軸常需展示「相對時間」(如「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/carbonuse 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 天后"
->addDays()、->startOfWeek())。DateTime::diff() + DateInterval::format() 手動構建,但 Carbon 體驗遠優。DateTimeZone)。time() 返回 Unix 時間戳不受影響,但跨天界限需用 DateTime 運算。DateInterval 的 y/m/d/h/i/s 屬性。relative_time 字段,定期任務刷新。相對時間函數是「寫一次、用到處」的典型工具函數,建議封裝到項目公共 helpers.php 或 Composer 包中統一維護。