1. 时间戳与标准日期转化
export function formatTime (time, format) {
let t = new Date(time)
let o = {
'M+': t.getMonth() + 1, // month
'd+': t.getDate(), // day
'h+': t.getHours(), // hour
'm+': t.getMinutes(), // minute
's+': t.getSeconds(), // second
'q+': Math.floor((t.getMonth() + 3) / 3), // quarter
'S': t.getMilliseconds() // millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (t.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1
? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
}
return format
}
使用方法:
formatTime (1552394170000, 'yyyy-MM-dd hh:mm:ss') // 结果是 2019-03-12 20:36:10
2. 相对时间处理
function pastDiffNow (pasttime, ymd = 'yyyy/MM/dd') {
let nowTime = new Date().getTime()
let timeDiff = nowTime - new Date(pasttime).getTime()
let sec = Math.floor(timeDiff / 1000)
let min = Math.floor(timeDiff / (1000 * 60))
let hour = Math.floor(timeDiff / (1000 * 60 * 60))
let day = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
let month = Math.floor(day / 30)
let year = Math.floor(month / 12)
if (year || month) return formatTime(pasttime, ymd + ' hh:mm:ss')
if (day === 1) {
return '昨天 ' + formatTime(pasttime, 'hh:mm:ss')
} else if (day === 2) {
return '前天 ' + formatTime(pasttime, 'hh:mm:ss')
} else if (day > 2) {
return (day + 1) + ' 天前'
}
if (hour) return hour + ' 小时前'
if (min < 30 && min > 0) {
return '半小时前'
} else if (min >= 30) {
return min + ' 分钟前'
}
if (sec) {
return sec + ' 秒前'
} else {
return '刚刚'
}
}
使用方法: 如果想要显示具体的时间格式,就要配合上一个formatTime 方法使用
pastDiffNow(1552394170000) // 21小时前
pastDiffNow(1552364170000) // 昨天 12:16:10