JS、jquery实现几分钟前、几小时前、几天前等时间差显示效果的代码实例分享
一、javascript函数实现:
//JavaScript函数:
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;
function getDateDiff(dateTimeStamp){
var now = new Date().getTime();
var diffValue = now - dateTimeStamp;
//var diffValue = now-getDateTimeStamp(dateTimeStamp);
if(diffValue < 0){
//若日期不符则弹出窗口告之
//alert("结束日期不能小于开始日期!");
}
var monthC =diffValue/month;
var weekC =diffValue/(7*day);
var dayC =diffValue/day;
var hourC =diffValue/hour;
var minC =diffValue/minute;
if(monthC>=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;
}
若你得到的时间格式不是时间戳,可以使用下面的JavaScript函数把字符串转换为时间戳, 本函数的功能相当于JS版的strtotime:
//js函数代码:字符串转换为时间戳
function getDateTimeStamp(dateStr){
return Date.parse(dateStr.replace(/-/gi,"/"));
}
代码2:
<script>
function jsDateDiff(publishTime){
var d_minutes,d_hours,d_days;
var timeNow = parseInt(new Date().getTime()/1000);
var d;
d = timeNow - publishTime;
d_days = parseInt(d/86400);
d_hours = parseInt(d/3600);
d_minutes = parseInt(d/60);
if(d_days>0 && d_days<4){
return d_days+"天前";
}else if(d_days<=0 && d_hours>0){
return d_hours+"小时前";
}else if(d_hours<=0 && d_minutes>0){
return d_minutes+"分钟前";
}else{
var s = new Date(publishTime*1000);
// s.getFullYear()+"年";
return (s.getMonth()+1)+"月"+s.getDate()+"日";
}
}
</script>