调用 semanticTime函数,动态分段生活化展示时间,包含
- 刚刚
- 几分钟前
- 几小时前
- 昨天
- 几天前
- isPrecise参数为true将展示详细时间 某年某月某日 时:分
// 语义化时间展示
function semanticTime(dateString, isPrecise){
if (!dateString) return ''
const date = new Date(Date.parse(dateString.replace(/-/g, "/")))
const diffTime = new Date()-date
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hours = date.getHours()
const minutes = date.getMinutes()
const yearMonthDay = year+'年'+month+'月'+day+'日'
const hoursMinutes = hours+':'+minutes
const allStr = yearMonthDay+' '+hoursMinutes
if (diffTime<1*60*1000){
return '刚刚'
} else if(diffTime<60*60*1000){
return Math.floor((diffTime / (1000 * 60))) + '分钟前'
} else if(diffTime<24*60*60*1000){
if (!isPrecise) {
return Math.floor((diffTime / (60 * 1000 * 60))) + '小时前'
} else {
return hoursMinutes
}
} else if(diffTime<2*24*60*60*1000){
return '昨天'+(isPrecise?' '+hoursMinutes:'')
} else {
if (!isPrecise) {
return Math.floor((diffTime / (24 * 60 * 1000 * 60))) + '天前'
} else {
return allStr
}
}
}
//const str = semanticTime('2022-12-2 12:42', ) // 21天前
const str = semanticTime('2022-12-2 12:42', 1) // 2022年12月2日 12:42
console.log('str is:', str)