1 function getDateDiff(dateTimeStamp){ 2 var minute = 1000 * 60; 3 var hour = minute * 60; 4 var day = hour * 24; 5 var halfamonth = day * 15; 6 var month = day * 30; 7 var now = new Date().getTime(); 8 var diffValue = now - dateTimeStamp; 9 if(diffValue < 0){return;} 10 var monthC = diffValue/month; 11 var weekC = diffValue/(7*day); 12 var dayC = diffValue/day; 13 var hourC = diffValue/hour; 14 var minC = diffValue/minute; 15 if(monthC >= 1){ 16 result = parseInt(monthC) + "月前"; 17 }else if(weekC >= 1){ 18 result = parseInt(weekC) + "周前"; 19 }else if(dayC >= 1){ 20 result = parseInt(dayC) +"天前"; 21 }else if(hourC >= 1){ 22 result = parseInt(hourC) +"小时前"; 23 }else if(minC >= 1){ 24 result = parseInt(minC) +"分钟前"; 25 }else{ 26 result = "刚刚"; 27 } 28 return result; 29 }
转换标准时间为时间戳:
1 function getDateTimeStamp(dateStr){ 2 return Date.parse(dateStr.replace(/-/gi,"/")); 3 }
调用:
1 var timeStr = '2018-05-16 15:02:20', 2 timeStamp = getDateTimeStamp(timeStr); 3 console.log(getDateDiff(timeStamp));