需求
实现一个消息通知,类似微信聊天一样,按时间显示刚刚,一个小时前,今天xx,昨天。。。。
export const dateTimeFormat = date => {
// auto 0
const autoZero = (n) => (String(n).length === 1 ? '0' : '') + n
// string to timestamp
const strToTimestamp = (str) => Date.parse(str.replace(/-/gi, '/'))
let oriSecond = strToTimestamp(date) / 1000
let curSecond = parseInt(new Date().getTime() / 1000)
let diffSecond = curSecond - oriSecond
let curDate = new Date(curSecond * 1000)
let oriDate = new Date(oriSecond * 1000)
let Y = oriDate.getFullYear()
let m = oriDate.getMonth() + 1
let d = oriDate.getDate()
let H = oriDate.getHours()
let i = oriDate.getMinutes()
// just
if (diffSecond < 60) {
// within a minute
return '刚刚'
} else if (diffSecond < 3600) {
// within an hour
return `${Math.floor(diffSecond / 60)}分钟前`
} else if (
curDate.getFullYear() === Y &&
curDate.getMonth() + 1 === m &&
curDate.getDate() === d
) {
return `今天${autoZero(H)}:${autoZero(i)}`
}
// yesterday
let mewDate = new Date((curSecond - 86400) * 1000)
if (mewDate.getFullYear() === Y && mewDate.getMonth() + 1 === m && mewDate.getDate() === d) {
return `昨天${autoZero(H)}:${autoZero(i)}`
} else if (curDate.getFullYear() === Y) {
return `${autoZero(m)}月${autoZero(d)}日`
}
return `${Y}年${autoZero(m)}月${autoZero(d)}日`
}