Vue 计算时间差,几分钟之前、几小时前、几天之前、几个月前

1 篇文章 0 订阅

上代码 创建组件【TimeDiff】

<template>
  <span style="font-size: 13px">{{ content }}</span>
</template>

<script>
export default {
  data () {
    return {
      content: '',
    }
  },
  props: {
    date: {
      type: String,
      default: new Date().toString()
    },
    time: {
      type: Number,
      default: 0,
      dateTimeStamp: ''
    }
  },
  mounted() {
    this.diffTime()
  },
  methods: {
    diffTime () {
        this.dateTimeStamp = this.time
        if (!this.dateTimeStamp) {
          if(!this.date) {
            return '刚刚'
          }
          this.dateTimeStamp = new Date(this.date).getTime()
        }
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;

        var now = new Date().getTime();
        var diffValue = now - this.dateTimeStamp;

        var monthC =diffValue/month;
        var weekC =diffValue/(7*day);
        var dayC =diffValue/day;
        var hourC =diffValue/hour;
        var minC =diffValue/minute;
        if (parseInt(monthC) >=1) {
          this.content = parseInt(monthC) + '个月前'
        } else if (parseInt(dayC) > 1) {
          this.content = parseInt(dayC) + '天前'
        } else if (parseInt(dayC) === 1) {
          this.content = '昨天'
        } else if(parseInt(hourC)>=1){
          this.content = parseInt(hourC) +"小时前";
        } else if(parseInt(minC)>=1){
          this.content = parseInt(minC) +"分钟前";
        } else {
          this.content = "刚刚";
        }
    }
  }
}
</script>

<style>

</style>

如何使用

1、可自行改成function用于js
2、Vue中使用
// script中引入
import TimeDiff from "../../components/TimeDiff";
// 注册组件
export default {
  components: {
     TimeDiff
   }
}
  // 使用
  <template>
  	<div>
  		// 使用date传值 传年月日时分秒
  		<TimeDiff date="2020-11-28 12:00:00"/>
  		// 使用time 传时间戳
  		<TimeDiff time="1606560899952"/>
  	</div>
  </template>
  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值