//实现时间转换,这篇文章发布时间为 2016/1/20 19:59:30 文章发表时间戳为:1453291170000于:11月前
function getDateDiff(dateTimeStamp){ var minute = 1000 * 60; var hour = minute * 60; var day = hour * 24; var halfamonth = day * 15; var month = day * 30; var now = new Date().getTime(); var diffValue = now - dateTimeStamp; if(diffValue < 0){return;} 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; } //转换标准时间为时间戳: function getDateTimeStamp(dateStr){ return Date.parse(dateStr.replace(/-/gi,"/")); }
参考:http://caibaojian.com/timestamp.html
另一个选择:
function formatMsgTime (timespan) { var dateTime = new Date(timespan); var year = dateTime.getFullYear(); var month = dateTime.getMonth() + 1; var day = dateTime.getDate(); var hour = dateTime.getHours(); var minute = dateTime.getMinutes(); var second = dateTime.getSeconds(); var now = new Date(); var now_new = Date.parse(now.toDateString()); //typescript转换写法 var milliseconds = 0; var timeSpanStr; milliseconds = now_new - timespan; if (milliseconds <= 1000 * 60 * 1) { timeSpanStr = '刚刚'; } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前'; } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前'; } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) { timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'; } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) { timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute; } else { timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute; } return timeSpanStr; };