1.首先第一种方法通过JS方式实现
function getDateDiff(dateTimeStamp){ dateTimeStamp=Date.parse(dateTimeStamp.replace(/-/gi,"/")); var minute = 1000 * 60; var hour = minute * 60; var day = hour * 24; var halfamonth = day * 15; var month = day * 30; var now = new Date().getTime(); var diffValue = now - dateTimeStamp; if(diffValue =1){ result="" + parseInt(monthC) + "月前"; } else if(weekC>=1){ result="" + parseInt(weekC) + "周前"; } else if(dayC>=1){ result=""+ parseInt(dayC) +"天前"; } else if(hourC>=1){ result=""+ parseInt(hourC) +"小时前"; } else if(minC>=1){ result=""+ parseInt(minC) +"分钟前"; }else result="刚刚"; return result;}
使用放法:getDateDiff('2017-08-08 18-18-18');
dateTimeStamp=Date.parse(dateTimeStamp.replace(/-/gi,"/"));
2.第二种方式通过PHP方式实现
function timeago($time){ $time = time()-strtotime($time); if(is_numeric($time)){ $value = array( "years" => 0, "days" => 0, "hours" => 0, "minutes" => 0, "seconds" => 0, ); if($time >= 31556926){ $value["years"] = floor($time/31556926); $time = ($time%31556926); $t = $value["years"].'年前'; } elseif(31556926 >$time && $time >= 86400){ $value["days"] = floor($time/86400); $time = ($time%86400); $t = $value["days"].'天前'; } elseif(86400 > $time && $time >= 3600){ $value["hours"] = floor($time/3600); $time = ($time%3600); $t = $value["hours"].'小时前'; } elseif(3600 > $time && $time >= 60){ $value["minutes"] = floor($time/60); $time = ($time%60); $t = $value["minutes"].'分钟前'; }else{ $t = $time.'秒前'; } return $t; }else{ return date('Y-m-d H:i:s',time()); } }
使用放法:timeago('2017-08-08 18-18-18');
如果要通过时间戳的方式即timeago('15654655665');方式 将下面这行代码替换第一行就可以了
$time = time()-$time;
这两种方式都是可以修改时间区间的 一般都是x分前 x小时前 x天前 x月前 x年前
这里附上一张效果图
希望可以帮到大家,有什么建议可以在下面留言
领取专属 10元无门槛券
私享最新 技术干货