在搞websocket的聊天时,遇到了一个小问题,就是判断列表的时间,有意思的是,怎么让它和微信一样展示,判断消息的时间,同一天的只显示时间,不是同一天但小于一天的“昨天”+时间显示,大于一天小于7天按星期几显示,其他的就按日期+时间显示
我这里的时间显示的格式为xxxx-xx-xx xx:xx:xx,在哪需要改动时间的显示样式,就在那调用函数formatSendTime
formatSendTime(sendTime) {
const now = new Date()
const sendDate = new Date(sendTime)
console.log(now, '11111', sendDate, 'shijian')
// 计算时间差(以毫秒为单位)
const timeDiff = now - sendDate
// console.log(timeDiff, '时间差')
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const startOfTargetDate = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate())
// 一天内的毫秒数
const oneDay = 24 * 60 * 60 * 1000
// 如果发送时间在当前时间之前
if (timeDiff < 0) {
return 'Invalid time' // 或者其他错误处理
}
// 发生在同一天
if (startOfToday.getTime() === startOfTargetDate.getTime()) {
return this.formatTime(sendDate)
}
// 如果发送时间在一天内
if (timeDiff < oneDay) {
return '昨天 ' + this.formatTime(sendDate)
}
// 如果发送时间在二天至七天内
if (timeDiff < 7 * oneDay) {
const weekday = this.getWeekday(sendDate)
return weekday + ' ' + this.formatTime(sendDate)
}
// 如果发送时间超过七天
return (
sendDate.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }) +
' ' +
this.formatTime(sendDate)
)
},
formatTime(date) {
// 格式化时间为“时:分”
const hours = date.getHours().toString().padStart(2, '0')
const minutes = date.getMinutes().toString().padStart(2, '0')
return hours + ':' + minutes
},
getWeekday(date) {
// 获取星期几的中文表示
const weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
return weekdays[date.getDay()]
},