2022-08-22T00:58:59.png

获取当前时间戳,与后端填写的时间戳进行计算即可.


<template>
  <div>
    {{date}}
  </div>
</template>
<script>
export default {
  data () {
    return {
      timeInterval: null,
      date: "",
    }
  },
  created () {
    // 进来先清楚定时器
    clearInterval(this.timeInterval);
    this.show_runtime();
  },
  methods: {
    show_runtime() {
      this.timeInterval = setInterval(() => {
        // 获取我初始时间
        const beginDate = new Date("2019-12-01 09:00:00");
        // 获取当前时间
        const nowDate = new Date();
        // 获取1年的毫秒数字 时 分 秒 毫秒 天
        const oneYearSecond = 24 * 60 * 60 * 1000 * 365;
        // 获取当月最后一天 因为有可能是28、30、31号
        const lastDay = new Date(nowDate.getFullYear(), nowDate.getMonth() + 1, 0).getDate();
        // 获取初始时间到当前时间的毫秒数
        const milliSecond = (nowDate.getTime() - beginDate.getTime());
        // 获取年份
        const year = milliSecond / oneYearSecond;
        const yearMathFloor = Math.floor(milliSecond / oneYearSecond);
        // 获取月份
        const month = (year - yearMathFloor) * 12;
        const monthMathFloor = Math.floor(month);
        // 获取日
        const day = (month - monthMathFloor) * lastDay;
        const dayMathFloor = Math.floor(day);
        // 获取时
        const hour = (day - dayMathFloor) * 24;
        const hourMathFloor = Math.floor(hour);
        // 获取分
        const minute = (hour - hourMathFloor) * 60;
        const minuteMathFloor = Math.floor(minute);
        // 获取秒
        const second = (minute - minuteMathFloor) * 60;
        const secondMathFloor = Math.floor(second);
        this.date = 
        `${yearMathFloor}年${monthMathFloor}月${dayMathFloor}天${hourMathFloor}时${minuteMathFloor}分${secondMathFloor}秒`;
      }, 500);
    }
  },
  destroyed () {
    clearInterval(this.timeInterval);
  }
}
</script>

发表评论