您现在的位置是:网站首页> php专栏 常见问题
php时间转换为几秒前、几分钟前、几小时前、几天前
亦然2019-07-30 12:54:25【常见问题】人已围观
简介我们经常看到有些网站上的文章发布时间显示的是几秒前、几分钟前、几小时前、几天前、几星期前、几个月前、几年前,这种显示效果一般就是根据“现在的时间”减去“发表的时间”等于“已经过去的时间”,然后对“已经过去的时间”进行处理来实现这种显示效果。
第一种:
/** * @Description: 将时间转换为几秒前、几分钟前、几小时前、几天前 * @Author: 亦然 * @param $the_time 需要转换的时间戳 * @return string */ function time_tran($the_time) { // $now_time = date("Y-m-d H:i:s", time()); $now_time = time(); $show_time = $the_time; $dur = $now_time - $show_time; if ($dur < 0) { return $the_time; } else { if ($dur < 60) { return $dur . '秒前'; } else { if ($dur < 3600) { return floor($dur / 60) . '分钟前'; } else { if ($dur < 86400) { return floor($dur / 3600) . '小时前'; } else { if ($dur < 259200) { // 3天内 return floor($dur / 86400) . '天前'; } else { if($dur < 31536000){ return date('m-d' ,$the_time); }else{ return date('Y-m-d',$the_time); } } } } } } }第二种:
/** * $time 文章的发布时间(格式为时间戳) * @return 返回可读性友好的时间格式 */ function friend_time($time) { $t=time()-$time; $f=array( '31536000'=>'年', '2592000'=>'个月', '604800'=>'星期', '86400'=>'天', '3600'=>'小时', '60'=>'分钟', '1'=>'秒' ); foreach ($f as $k=>$v) { if (0 !=$c=floor($t/(int)$k)) { return $c.$v.'前'; } } }
很赞哦!()
上一篇:api接口限制访问
下一篇:tp5定时任务,定时清理日志文件