输入:过去的 Unix 时间戳。输出:人类可读的相对时间字符串,自动切换单位(秒/分/时/天/月/年)。
<?php
function timeAgo($timestamp, $lang = 'zh') {
$diff = time() - (int)$timestamp;
if ($diff < 0) $diff = 0;
$periods = array(
'year' => 31556926,
'month' => 2629744,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1,
);
$labels = array(
'zh' => array('year'=>'年','month'=>'月','week'=>'周','day'=>'天','hour'=>'小时','minute'=>'分钟','second'=>'秒'),
'en' => array('year'=>'y','month'=>'m','week'=>'w','day'=>'d','hour'=>'h','minute'=>'m','second'=>'s'),
);
$l = $labels[$lang];
foreach ($periods as $unit => $seconds) {
if ($diff >= $seconds) {
$val = floor($diff / $seconds);
return $val . $l[$unit] . ($lang === 'zh' ? '前' : ' ago');
}
}
return $lang === 'zh' ? '刚刚' : 'just now';
}
// 扩展:支持 "30m", "2h", "4d" 格式判断是否过期
function time_is_older_than($t, $check_time) {
$t = strtolower($t);
$unit = substr(preg_replace('/[^a-z]/', '', $t), 0, 1);
$val = (int)preg_replace('/[^0-9]/', '', $t);
$map = array('s'=>1, 'm'=>60, 'h'=>3600, 'd'=>86400, 'y'=>31556926);
if (!isset($map[$unit])) die('Unknown time format');
$ts = $val * $map[$unit];
return $check_time < (time() - $ts);
}
// 测试
$time = strtotime('-2 hours');
echo timeAgo($time); // 2小时前
// 过期检查
if (time_is_older_than('30m', $time)) echo "超过30分钟";
function timeAgoPrecise($ts, $maxUnits = 2) {
$diff = time() - $ts;
$units = array(
'year' => 31556926,
'month' => 2629744,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1,
);
$parts = array();
foreach ($units as $u => $s) {
if ($diff >= $s) {
$v = floor($diff / $s);
$parts[] = $v . $u . ($v > 1 ? 's' : '');
$diff -= $v * $s;
if (count($parts) >= $maxUnits) break;
}
}
return implode(' ', $parts) . ' ago';
}
现代前端推荐使用 Day.js + relativeTime 插件,浏览器端实时更新,无需服务端渲染:
dayjs.extend(relativeTime);
dayjs(timestamp * 1000).fromNow(); // "2 hours ago"