最近在做項目的時候,需要把后台返回的時間轉換成幾秒前、幾分鍾前、幾小時前、幾天前等的格式;后台返回的時間格式為:2015-07-30 09:36:10,需要根據當前的時間與返回的時間進行對比,最后顯示成幾秒前、幾分鍾前、幾小時前、幾天前的形式。
1.由於返回的時間是字符串格式,所以要先轉換成時間戳
//字符串轉換為時間戳
function getDateTimeStamp (dateStr) {
return Date.parse(dateStr.replace(/-/gi,"/"));
}
2.將返回的時間戳與當前時間戳進行比較,轉換成幾秒前、幾分鍾前、幾小時前、幾天前的形式。
function getDateDiff (dateStr) { var publishTime = getDateTimeStamp(dateStr)/1000, d_seconds, d_minutes, d_hours, d_days, timeNow = parseInt(new Date().getTime()/1000), d, date = new Date(publishTime*1000), Y = date.getFullYear(), M = date.getMonth() + 1, D = date.getDate(), H = date.getHours(), m = date.getMinutes(), s = date.getSeconds(); //小於10的在前面補0 if (M < 10) { M = '0' + M; } if (D < 10) { D = '0' + D; } if (H < 10) { H = '0' + H; } if (m < 10) { m = '0' + m; } if (s < 10) { s = '0' + s; } d = timeNow - publishTime; d_days = parseInt(d/86400); d_hours = parseInt(d/3600); d_minutes = parseInt(d/60); d_seconds = parseInt(d); if(d_days > 0 && d_days < 3){ 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 if (d_seconds < 60) { if (d_seconds <= 0) { return '剛剛發表'; }else { return d_seconds + '秒前'; } }else if (d_days >= 3 && d_days < 30){ return M + '-' + D + ' ' + H + ':' + m; }else if (d_days >= 30) { return Y + '-' + M + '-' + D + ' ' + H + ':' + m; } }
3.使用方法:
dateStr:返回的時間字符串,格式如:2015-07-30 09:36:10
// 轉換后的結果
var str = getDateDiff(dateStr);
// 在控制台輸出結果
console.log(str);