php,js两种方法将时间转换为过去多久以前

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年前

这里附上一张效果图

希望可以帮到大家,有什么建议可以在下面留言

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181013G1L8T600?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。

扫码关注云+社区

领取腾讯云代金券