給定秒數差值 $last_time,輸出「剛剛」、「N 分鐘前」、「N 小時前」、「N 天前」、「N 個月前」。
function human_time_diff($seconds) {
if ($seconds < 60) return '剛剛';
$minutes = floor($seconds / 60);
if ($minutes < 60) return "$minutes 分鐘前";
$hours = floor($minutes / 60);
if ($hours < 24) return "$hours 小時前";
$days = floor($hours / 24);
if ($days < 30) return "$days 天前";
$months = floor($days / 30);
if ($months < 12) return "$months 個月前";
return floor($months / 12) . ' 年前';
}
// 使用範例
$last_time = time() - strtotime('2023-09-01 12:00:00');
echo human_time_diff($last_time); // 輸出如 "2 個月前"
if ($last_time > 2592000) // 30 天
$last_update = intval($last_time/2592000) . "個月";
elseif ($last_time > 604800) // 7 天
$last_update = intval($last_time/604800) . "個星期";
elseif ($last_time > 86400) // 1 天
$last_update = intval($last_time/86400) . "天";
else
$last_update = "今天";
上述為簡化版,實際專案建議使用完整函數支援秒/分/時/天/月/年全階層。
現代前後端分離架構,後端回傳 ISO 8601 時間(2023-10-01T12:00:00Z),前端用 dayjs().fromNow() 自動顯示相對時間,支援多語系、無需後端邏輯。