来源于从未谋面的前同事遗产,我不知道他/她自己写的还是转的,不确定来源
/**
* 词义化时间
*
* @access public
* @param string $from 起始时间
* @param string $now 终止时间
* @return string
*/
public static function dateWord($from, $now)
{
// 如果不是同一年
if (idate('Y', $now) != idate('Y', $from)) {
return date('Y年m月d日', $from);
}
// 以下操作同一年的日期
$seconds = $now - $from;
$days = idate('z', $now) - idate('z', $from);
// 如果是同一天
if ($days == 0) {
// 如果是一小时内
if ($seconds < 3600) {
// 如果是一分钟内
if ($seconds < 60) {
if (3 > $seconds) {
return '刚刚';
} else {
return sprintf('%d秒前', $seconds);
}
}
return sprintf('%d分钟前', intval($seconds / 60));
}
return sprintf('%d小时前', idate('H', $now) - idate('H', $from));
}
// 如果是昨天
if ($days == 1) {
return sprintf('昨天 %s', date('H:i', $from));
}
// 如果是前天
if ($days == 2) {
return sprintf('前天 %s', date('H:i', $from));
}
// 如果是7天内
if ($days < 7) {
return sprintf('%d天前', $days);
}
// 超过一周
return date('n月j日', $from);
}