其他分享
首页 > 其他分享> > Vue 计算时间差,几分钟之前、几小时前、几天之前、几个月前

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>

标签:dateTimeStamp,Vue,diffValue,之前,时间差,content,parseInt,var,else
来源: https://blog.csdn.net/sinat_34780955/article/details/110289302