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

上代码

<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>
上一篇:javascript中字符串和数字之间互相转换的方法总结


下一篇:根据入职日期计算工龄