vue对于时间的处理---适用于聊天页面的时间显示

2023-08-05 11:25:45 假如这个就是我们要传的时间字符串

比如今天是2023-08-05(同一天):现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回

11:25

比如今天是2023-08-06(前一天):现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回

昨日11:25

比如今天是2023-08-07或者2023-08-10或2023-12-30:现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回

08-05 11:25

比如今天是2024-08-07(24年任何一个日期):现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回

2023-08-05 11:25

适用于聊天上边的时间显示

 //时间处理
    formatDate(dateTime) {
      const now = new Date();
      const date = new Date(dateTime);

      if (date.toDateString() === now.toDateString()) {
        // 今天的日期,返回时间 HH:mm
        return this.formatTime(date);
      } else if (date.toDateString() === new Date(now.getTime() - 86400000).toDateString()) {
        // 昨天的日期,返回 "昨日 HH:mm"
        return "昨日 " + this.formatTime(date);
      } else if (date.getFullYear() === now.getFullYear()) {
        // 今年的日期,返回 MM-dd HH:mm
        return this.formatDateOnly(date) + " " + this.formatTime(date);
      } else {
        // 去年及以前的日期,返回 yyyy-MM-dd HH:mm
        return this.formatFullDate(date) + " " + this.formatTime(date);
      }
    },
    formatTime(date) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    formatDateOnly(date) {
      return date.toLocaleDateString([], { month: '2-digit', day: '2-digit' });
    },
    formatFullDate(date) {
      return date.toISOString().slice(0, 10);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我不是码神(dn)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值