<?php
/**
* 人性化时间差函数
*
* @param string|int $time 时间戳或日期字符串
* @param string $format 超过一定时间后的显示格式(默认:Y-m-d)
* @return string
*/
function timeAgo($time, $format = 'Y-m-d') {
// 如果是日期字符串,转换为时间戳
if (!is_numeric($time)) {
$time = strtotime($time);
}
// 如果转换失败,返回原值
if (!$time) {
return '未知时间';
}
// 当前时间戳
$now = time();
// 计算时间差(秒)
$diff = $now - $time;
// 未来时间处理(容错处理,时间在未来)
if ($diff < 0) {
$diff = abs($diff);
$future = true;
} else {
$future = false;
}
// 定义时间段
$second = 1;
$minute = 60;
$hour = 3600;
$day = 86400;
$week = 604800;
$month = 2592000; // 30天
$year = 31536000; // 365天
// 获取具体分钟数、小时数等(用于精确计算)
$minutes = floor($diff / $minute);
$hours = floor($diff / $hour);
$days = floor($diff / $day);
$weeks = floor($diff / $week);
$months = floor($diff / $month);
$years = floor($diff / $year);
$prefix = $future ? '还' : '';
$suffix = $future ? '后' : '前';
// 判断时间范围
if ($diff < $minute) { // 小于60秒
return $future ? '刚才' : '刚刚';
} elseif ($diff < $hour) { // 小于60分钟
return $minutes . '分钟' . $suffix;
} elseif ($diff < $day) { // 小于24小时
if ($hours == 1 && !$future && $diff < $day/2) {
return '1小时' . $suffix;
}
return $hours . '小时' . $suffix;
} elseif ($diff < $day * 2) { // 小于48小时
if ($days == 1 && !$future) {
// 判断是否为昨天(简单判断24-48小时内且不是今天)
$today_start = strtotime('today');
if ($time < $today_start && $time >= strtotime('yesterday')) {
return '昨天';
}
}
return $days . '天' . $suffix;
} elseif ($diff < $week) { // 小于7天
return $days . '天' . $suffix;
} elseif ($diff < $month) { // 小于30天
return $weeks . '周' . $suffix;
} elseif ($diff < $year) { // 小于365天
return $months . '个月' . $suffix;
} else { // 大于等于365天
return $years . '年' . $suffix;
}
}
// 测试示例
$testTimes = [
time() - 10, // 10秒前
time() - 30, // 30秒前
time() - 3600, // 1小时前
time() - 3600 * 2, // 2小时前
time() - 86400, // 1天前
time() - 86400 * 2, // 2天前
time() - 86400 * 3, // 3天前
time() - 86400 * 7, // 1周前
time() - 86400 * 30, // 1个月前
time() - 86400 * 365, // 1年前
time() + 3600, // 1小时后
];
foreach ($testTimes as $testTime) {
echo date('Y-m-d H:i:s', $testTime) . ' => ' . timeAgo($testTime) . "\n";
}
?>
或者更简洁的版本:

<?php
/**
* 简洁版人性化时间差
*/
function friendlyTime($time) {
// 统一转换为时间戳
$timestamp = is_numeric($time) ? $time : strtotime($time);
if (!$timestamp) return '未知时间';
$diff = time() - $timestamp;
// 未来时间处理
if ($diff < 0) {
return '时间在未来';
}
// 各时间段
$periods = [
'年' => 31536000,
'个月' => 2592000,
'周' => 604800,
'天' => 86400,
'小时' => 3600,
'分钟' => 60,
'秒' => 1
];
// 找到合适的时间段
foreach ($periods as $name => $seconds) {
$result = floor($diff / $seconds);
if ($result >= 1) {
return $result . ' ' . $name . '前';
}
}
return '刚刚';
}
?>
核心功能:
- 支持时间戳和日期字符串输入
- 自动输出“刚刚”、“X分钟前”、“X小时前”、“昨天”、“X天前”等
- 支持未来时间的处理(如“X小时后”)
- 简单易用,代码清晰
使用示例:
echo friendlyTime(time() - 3600); // 输出:1 小时前
echo friendlyTime('2023-01-01 12:00:00'); // 处理日期字符串
?>