You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Laravel项目不使用moment.js实现X秒/分/小时前相对时间显示方案

实现方案

直接修改readableDate方法即可,原生JavaScript即可实现,无额外依赖:

methods: {
  readableDate (date) {
    const timeDiff = Date.now() - new Date(date).getTime()
    const units = [
      { value: 31536000000, label: '年' },
      { value: 2592000000, label: '个月' },
      { value: 86400000, label: '天' },
      { value: 3600000, label: '小时' },
      { value: 60000, label: '分钟' },
      { value: 1000, label: '秒' }
    ]
    for (const unit of units) {
      const count = Math.floor(timeDiff / unit.value)
      if (count >= 1) {
        return `${count}${unit.label}前`
      }
    }
    return '刚刚'
  }
}
  • 原有Vue模板代码无需修改,{{ readableDate(message.created_at) }}可直接沿用
  • 自动根据时间差匹配最优单位输出,例如30秒前、15分钟前、2小时前等
  • 兼容所有JS Date对象支持解析的时间输入格式

如果需要适配未来时间场景(显示X秒后类格式),可使用扩展版本:

methods: {
  readableDate (date) {
    const targetTime = new Date(date).getTime()
    const timeDiff = Date.now() - targetTime
    const suffix = timeDiff >= 0 ? '前' : '后'
    const absDiff = Math.abs(timeDiff)
    const units = [
      { value: 31536000000, label: '年' },
      { value: 2592000000, label: '个月' },
      { value: 86400000, label: '天' },
      { value: 3600000, label: '小时' },
      { value: 60000, label: '分钟' },
      { value: 1000, label: '秒' }
    ]
    for (const unit of units) {
      const count = Math.floor(absDiff / unit.value)
      if (count >= 1) {
        return `${count}${unit.label}${suffix}`
      }
    }
    return '刚刚'
  }
}

内容的提问来源于stack exchange,提问作者ArcticMediaRyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:06:03