小白一枚,今天遇到一个问题,如果上一条消息和最新消息在三分钟内就不显示时间戳,否则就显示时间戳的要求。通过对字符串截取,再比较实时时间完成这个要求。代码可能比较冗余,但是逻辑很简单易懂。
data: {
msgList: [
{
speaker: 'server',
contentType: 'text',
content: '欢迎来到英雄联盟,敌军还有30秒到达战场,请做好准备!',
time: '2024年12月01日 12:00'
},
{
speaker: 'server',
contentType: 'text',
content: '欢迎',
time: '2024年12月01日 12:34'
}
]
formatTime: function () {
var date = new Date()
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
let msgListLength = this.data.msgList.length
//获取最近一条消息的时间
const msgListLast = this.data.msgList[msgListLength - 1].time
//判断和目前的时间的差距是否小于三分钟
let hide =
hour == msgListLast.substr(-5, 2) &&
(minute - msgListLast.substr(-2, 2) < 3 || minute - msgListLast.substr(-2, 2) < -57)
if (minute < 10) {
return { realTime: year + '年' + month + '月' + day + '日' + ' ' + hour + ':0' + minute, hide: hide }
} else {
return { realTime: year + '年' + month + '月' + day + '日' + ' ' + hour + ':' + minute, hide: hide }
}
}
sendmsg: function () {
//点击发送消息后进行判断,并添加最新的消息内容、时间、是否隐藏等信息
if (this.data.textVal) {
const msgList = this.data.msgList
const time = this.formatTime()
msgList.push({
speaker: 'customer',
contentType: 'text',
content: this.data.textVal,
time: time.realTime,
hide: time.hide
})
this.setData({
textVal: '',
msgList: msgList,
toView: 'msg-' + (msgList.length - 1)
})
} else {
wx.showToast({
title: '内容为空',
duration: 800,
icon: 'none',
mask: true
})
}
}