php把时间转换为友好时间段,如刚刚、几分钟前、几小时前、几天前的简单函数代码。通过把时间格式转换为时间戳,并把当前的时间戳减去之前时间的时间戳,相减后的时间戳除以相对应的秒数得到刚刚、几分钟前、几小时前、几天前的展示。
代码详细:/*
* @param $posttime 时间:2017-08-12 18:18:18
*/
function time_ago($posttime){
//当前时间的时间戳
$nowtimes = strtotime(date('Y-m-d H:i:s'),time());
//之前时间参数的时间戳
$posttimes = strtotime($posttime);
//相差时间戳
$counttime = $nowtimes - $posttimes;
//进行时间转换
if($counttime<=10){
return '刚刚';
}else if($counttime>10 && $counttime<=30){
return '刚才';
}else if($counttime>30 && $counttime<=60){
return '刚一会';
}else if($counttime>60 && $counttime<=120){
return '1分钟前';
}else if($counttime>120 && $counttime<=180){
return '2分钟前';
}else if($counttime>180 && $counttime<3600){
return intval(($counttime/60)).'分钟前';
}else if($counttime>=3600 && $counttime<3600*24){
return intval(($counttime/3600)).'小时前';
}else if($counttime>=3600*24 && $counttime<3600*24*2){
return '昨天';
}else if($counttime>=3600*24*2 && $counttime<3600*24*3){
return '前天';
}else if($counttime>=3600*24*3 && $counttime<=3600*24*20){
return intval(($counttime/(3600*24))).'天前';
}else{
return $posttime;
}
}
如果要加入几星期前、几月前、几年前可以按照上面的代码一次类推。在文章和帖子或留言的时间中用的最多的一个功能,代码简单易理解。