window.onload = function(){ var show_times = $(".times span"); for(var i=0;i<show_times.length;i++){ var dateStr = show_times[i].innerHTML; var dateTimeStamp = Date.parse(dateStr.replace(/-/gi,"/")); var minute = 1000 * 60; var hour = minute * 60; var day = hour * 24; var month = day * 30; //获取当前时间 var now = new Date().getTime(); var diffValue = now - dateTimeStamp; var monthC =diffValue/month; var weekC =diffValue/(7*day); var dayC =diffValue/day; var hourC =diffValue/hour; var minC =diffValue/minute; if(monthC>=1){ show_times[i].innerHTML = dateStr; } else if(weekC>=1){ result="发表于" + parseInt(weekC) + "周前"; show_times[i].innerHTML = result; } else if(dayC>=1){ result="发表于"+ parseInt(dayC) +"天前"; show_times[i].innerHTML = result; } else if(hourC>=1){ result="发表于"+ parseInt(hourC) +"小时前"; show_times[i].innerHTML = result; } else if(minC>=1){ result="发表于"+ parseInt(minC) +"分钟前"; show_times[i].innerHTML = result; }else{ result="发表于1分钟内"; show_times[i].innerHTML = result; } } }
很浅显易懂的js代码 大家基本上一看就懂了
用javascript写一个显示时间差 几分钟前 几小时前 几天前 几周前 大于一个月显示日期
原文:http://www.cnblogs.com/jingmin/p/6308891.html