在一些网站上,常常看到刚发表的留言显示为“刚刚”,时间长一些的,显示为:“几天前”,“几小时前”等等,那么这个怎么来实现呢?我们其实没有必要在数据库中对这些进行格式化,完全可以交给客户端进行显示,网上有许多JS写的,那么现在封闭成了一个Jquery的插件,代码如下:
var dateTimeStamp = varparam ? Date.parse(varparam.replace(/-/gi,"/")) : new Date().getTime();
var now = new Date().getTime();
var diffValue = now - 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){
return varparam;
}
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="刚刚发表";
var now = new Date().getTime();
var diffValue = now - 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){
return varparam;
}
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;
这是主要的代码,具体文件,可以下载附件: 下载