PHP将时间显示为几天前、几周前、几个月前、几年前
将时间格式化显示为:刚刚、几分钟前、几小时前、今天、昨天、前天、大前天、几天前、几周前、几个月前、几年前。
目前逻辑,60秒内显示为刚刚,60分钟内显示为几分钟前,12小时内显示为几小时前,12-24小时显示为今天,24小时至48小时显示为昨天,48-72小时为前天,72-96小时为大前天,7天内显示为几天前,30天内显示为几周前,1-12个月显示为几个月前,1-5年显示为几年前,5年以上显示为“年-月-日 小时:分钟”,具体效果请参见熊海博客时间显示效果。
/** * 时间格式化显示 * Author:熊海 * Time:2021-06-20 10:30 * Website:http://www.imxh.cn * @param unknown $time */ function tranTime($time) { $nowtime = time(); $difference = $nowtime - $time; switch ($difference) { case $difference <= '60' : $view = '刚刚'; break; case $difference > '60' && $difference <= '3600' : $view = floor($difference / 60) . '分钟前'; break; case $difference > '3600' && $difference <= '43200' : $view = floor($difference / 3600) . '小时前'; break; case $difference > '43200' && $difference <= '86400' : $view = '今天 '.date('H:i',$time); break; case $difference > '86400' && $difference <= '172800' : $view ='昨天 '.date('H:i',$time); break; case $difference > '172800' && $difference <= '259200' : $view ='前天 '.date('H:i',$time); break; case $difference > '259200' && $difference <= '345600' : $view ='大前天 '.date('H:i',$time); break; case $difference > '86400' && $difference <= '604800' : $view = floor($difference / 86400) . '天前 '.date('H:i',$time); break; case $difference > '604800' && $difference <= '2592000' : $view = floor($difference / 604800) . '周前 '.date('m-d H:i',$time); break; case $difference > '2592000' && $difference <= '31536000': $view = floor($difference / 2592000) . '个月前 '.date('m-d H:i',$time); break; case $difference > '31536000' && $difference <= '157680000': $view = floor($difference / 31536000) . '年前 '.date('Y-m-d H:i',$time); break; case $difference > '157680000': $view = date('Y-m-d H:i',$time); break; } return $view; }
其中今天、昨天、前天、大前天,是按照24小时为一天算的,可能会跨天,造成显示不是很准确,介意的可以去掉。
/** * 时间格式化显示,去掉今天、昨天、前天、大前天,显示相当准确。 * Author:熊海 * Time:2021-06-20 10:30 * Website:http://www.imxh.cn * @param unknown $time */ function tranTime($time) { $nowtime = time(); $difference = $nowtime - $time; switch ($difference) { case $difference <= '60' : $view = '刚刚'; break; case $difference > '60' && $difference <= '3600' : $view = floor($difference / 60) . '分钟前'; break; case $difference > '3600' && $difference <= '86400' : $view = floor($difference / 3600) . '小时前'; break; case $difference > '86400' && $difference <= '604800' : $view = floor($difference / 86400) . '天前 '.date('H:i',$time); break; case $difference > '604800' && $difference <= '2592000' : $view = floor($difference / 604800) . '周前 '.date('m-d H:i',$time); break; case $difference > '2592000' && $difference <= '31536000': $view = floor($difference / 2592000) . '个月前 '.date('m-d H:i',$time); break; case $difference > '31536000' && $difference <= '157680000': $view = floor($difference / 31536000) . '年前 '.date('Y-m-d H:i',$time); break; case $difference > '157680000': $view = date('Y-m-d H:i',$time); break; } return $view; }
共 1 条评论