if (!function_exists('time_ago')) {
/**
* 返回指定时间戳为当前时间戳的几秒前、几分钟前、几小时前…
* @param int $timestamp
* @return string || null
*/
function time_ago($timestamp) {
if (!$timestamp) return;
$difference = time() - $timestamp; //计算时间差
if ($difference < 10) return '刚刚'; //小于10秒判定为刚刚
// 定义计算数组对应的返回字符串
$intervals = array (
12 * 30 * 24 * 60 * 60 => '年前',
30 * 24 * 60 * 60 => '个月前',
7 * 24 * 60 * 60 => '周前',
24 * 60 * 60 => '天前',
60 * 60 => '小时前',
60 => '分钟前',
1 => '秒前',
);
foreach ($intervals as $second => $unit) {
$value = $difference / $second;
if ($value >= 1) return round($value) . $unit;
};
}
}