自定义函数:<?php
date_default_timezone_set('PRC'); // 设置时区,如果已经设置可以删除
function timeFormat( $timestamp ) {
$curTime = time();
$space = $curTime - $timestamp;
if($space < 60) { // 一分钟以内
$string = "刚刚";
return $string;
} elseif( $space < 3600 ) { // 一小时前之内
$string = floor($space / 60) . "分钟前";
return $string;
}
$curtimeArray = getdate($curTime);
$timeArray = getDate($timestamp);
if( $curtimeArray['year'] == $timeArray['year'] ) { // 同一年
if($curtimeArray['yday'] == $timeArray['yday']) { // 同一天
$format = "%H:%M";
$string = strftime($format, $timestamp);
return "今天 {$string}";
} elseif(($curtimeArray['yday'] - 1) == $timeArray['yday']) { // 昨天
$format = "%H:%M";
$string = strftime($format, $timestamp);
return "昨天 {$string}";
} else {
$string = sprintf("%d月%d日 d:d", $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
return $string;
}
}
$string = sprintf("%d年%d月%d日 d:d", $timeArray['year'], $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
return $string;
}使用示例:
echo sprintf("%d: %s\n", time(), timeFormat(time()));
echo sprintf("%d: %s\n", time()-720, timeFormat(time()-720));
echo sprintf("%d: %s\n", time()-10800, timeFormat(time()-10800));
echo sprintf("%d: %s\n", time()-86400, timeFormat(time()-86400));
echo sprintf("%d: %s\n", time()-86400*123, timeFormat(time()-86400*123));
echo sprintf("%d: %s\n", time()-86400*400, timeFormat(time()-86400*400));输出结果:1476155551: 刚刚
1476154831: 12分钟前
1476144751: 今天 08:12
1476069151: 昨天 11:12
1465528351: 6月10日 11:12
1441595551: 2015年9月7日 11:1