如何用js实现发布了多久的时间描述

文章资讯 2020-06-14 17:17:51

如何用js实现发布了多久的时间描述

<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title<title>
<head>
<script>
functiongetTs(time){
vararr=time.split([-:]),
_date=newDate(arr[0],arr[1]-1,arr[2],arr[3],arr[4],arr[5]),
timeStr=Date.parse(_date)
returntimeStr
}functionhandlePublishTimeDesc(post_modified){
拿到当前时间戳和发布时的时间戳,然后得出时间戳差
varcurTime=newDate();
varpostTime=newDate(post_modified);部分浏览器不兼容此转换建议所以对此进行补充(指定调用自己定义的函数进行生成发布时间的时间戳)vartimeDiff=curTime.getTime()-postTime.getTime();
上面一行代码可以换成以下(兼容性的解决)
vartimeDiff=curTime.getTime()-getTs(post_modified);单位换算
varmin=60*1000;
varhour=min*60;
varday=hour*24;
varweek=day*7;
varmonth=week*4;
varyear=month*12;计算发布时间距离当前时间的周、天、时、分
varexceedyear=Math.floor(timeDiffyear);
varexceedmonth=Math.floor(timeDiffmonth);
varexceedWeek=Math.floor(timeDiffweek);
varexceedDay=Math.floor(timeDiffday);
varexceedHour=Math.floor(timeDiffhour);
varexceedMin=Math.floor(timeDiffmin);
最后判断时间差到底是属于哪个区间,然后returnif(exceedyear<100&&exceedyear>0){
returnexceedyear+'年前';
}else{
if(exceedmonth<12&&exceedmonth>0){
returnexceedmonth+'月前';
}else{
if(exceedWeek<4&&exceedWeek>0){
returnexceedWeek+'星期前';
}else{
if(exceedDay<7&&exceedDay>0){
returnexceedDay+'天前';
}else{
if(exceedHour<24&&exceedHour>0){
returnexceedHour+'小时前';
}else{
returnexceedMin+'分钟前';
}
}
}
}
}
}
window.onload(alert(handlePublishTimeDesc("2020-6-1315:33:0.0")));<script>
<body><body>
<html>