vue中如何改变时间戳或标准格式的时间为几天前的形式

如果你在vue当中得到的是时间格式是时间戳格式或者是标准的时间格式(比如:2020-09-08 12:12:34),然后想让这些种格式变成几天前、几小时前的这种输出的话,我们需要做的是什么?
首先写一个函数,该函数用来处理当前时间减去得到的时间最后显示出来的‘几天前、几小时前’的格式,那这个函数我是把它放在了外面然后在组件中通过过滤方式来进行调用

export function timeago(dateTimeStamp) {
    // dateTimeStamp是一个时间毫秒,注意时间戳是秒的形式,在这个毫秒的基础上除以1000,就是十位数的时间戳。13位数的都是时间毫秒。
    let minute = 1000 * 60;      //把分,时,天,周,半个月,一个月用毫秒表示
    let hour = minute * 60;
    let day = hour * 24;
    let week = day * 7;
    //var halfamonth = day * 15;
    let month = day * 30;

    let now = new Date().getTime();   //获取当前时间毫秒
    let diffValue = now - dateTimeStamp;//时间差

    if (diffValue < 0) { return; }

    let minC = diffValue / minute;  //计算时间差的分,时,天,周,月
    let hourC = diffValue / hour;
    let dayC = diffValue / day;
    let weekC = diffValue / week;
    let monthC = diffValue / month;
    let result
    if (monthC >= 1) {
        result = "" + parseInt(monthC) + "月前";
    }
    else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
    }
    else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
    }
    else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
    }
    else if (minC >= 1) {
        result = "" + parseInt(minC) + "分钟前";
    } else
        result = "刚刚";
    return result;
}

该函数目前主要就是处理了时间戳的形式转变为所需要的格式,如果是标准格式的话,则需要在组件过滤的时候再加一些方法

filters:{
    Timer: function(str) {
      let stringTime =new Date(str.replace(/-/g, "/"));
      let date = stringTime.getTime();
      return timeago(date)
    }
  },

在使用的时候,比如有一个时间time(time=‘2020-09-08 13:06:43’)需要展示为所需格式,则

<div>{{time|Timer(time)}}</div>time为想要转换的时间
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

是小许同学吖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值