最近在做一个类似发帖的模块,要显示例如:几秒前,几分钟前,几天前等的功能,使用的TP5,写了个公共函数,代码如下:
1 function TimeRule($time) 2 { 3 $startdate = $time; 4 $enddate = date('Y-m-d H:i:s'); 5 $date = floor((strtotime($enddate) - strtotime($startdate)) / 86400); 6 $hour = floor((strtotime($enddate) - strtotime($startdate)) % 86400 / 3600); 7 $minute = floor((strtotime($enddate) - strtotime($startdate)) % 86400 % 3600 / 60); 8 $second = floor((strtotime($enddate) - strtotime($startdate)) % 86400 % 60); 9 10 if ($date > 90) 11 { 12 return '很久前'; 13 } 14 elseif ($date >= 30 && $date <= 90) 15 { 16 return floor($date / 30) . '个月前'; 17 } 18 elseif ($date > 0 && $date < 30) 19 { 20 return $date . '天前'; 21 } 22 elseif ($hour < 24 && $hour > 0) 23 { 24 return $hour . '小时前'; 25 } 26 elseif ($minute < 60 && $minute > 0) 27 { 28 return $minute . '分钟前'; 29 } 30 elseif ($second < 60 && $second > 0) 31 { 32 return $second . '秒前'; 33 } 34 }
在控制器中调用公共函数:
1 public function timeShow() 2 { 3 $startdate = "2017-6-30 7:40:00"; 4 5 $t = TimeRule($startdate); 6 echo $t; 7 8 }