微信小程序实现三分钟内连续发送消息不显示时间戳

小白一枚,今天遇到一个问题,如果上一条消息和最新消息在三分钟内就不显示时间戳,否则就显示时间戳的要求。通过对字符串截取,再比较实时时间完成这个要求。代码可能比较冗余,但是逻辑很简单易懂。

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
      })
    }
  }

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值