时间戳:
时间戳是自 1970 年 1 月 1 日(00:00:00 GMT)至当前时间的总秒数
既然是秒数,那么在js中换成时间日期格式就不是什么难事了。
将时间戳转换成日期格式:
function transDate(merStr) { var n = merStr; var date = new Date(n); var Y = date.getFullYear() + '-'; var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); return (Y + M + D) }
讲时间戳转换成几分钟前/几小时/几天前:
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()); 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; };