vue/uniapp 仿微信聊天列表的日期显示

在搞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()]
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值