倒计时 / 多少月、天、时、分前

<template>
  <div class="number">
    <div>倒计时时间:{{ dateTit }}</div>
    <div>多少天后{{ gtePastTimesDate(formerly) }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 倒计时参数
      dateTit: null, //页面显示倒计时参数
      remTime: null, //关闭定时器变量
      endTime: "2022-07-13 04:20:00", //倒计时结束时间

      // 多少月、天、时、分前
      formerly: "2022-7-12 21:00:00",
    };
  },
  mounted() {
    // 加载页面时调用,倒计时函数
    this.Time();
  },
  methods: {
    // 倒计时
    countDown() {
      let cancelTime = new Date(this.endTime).getTime(); //截止时间 时间戳
      let date = new Date().getTime();
      let difference = cancelTime - date; //时间差

      let d, h, m, s;
      d = Math.floor(difference / 1000 / 60 / 60 / 24);
      h = Math.floor((difference / 1000 / 60 / 60) % 24);
      m = Math.floor((difference / 1000 / 60) % 60);
      s = Math.round((difference / 1000) % 60);
      d = d < 10 ? "0" + d : d;
      s = s < 10 ? "0" + s : s;
      m = m < 10 ? "0" + m : m;
      h = h < 10 ? "0" + h : h;
      if (difference > 0) {
        this.dateTit = `${d}${h}${m}${s}`;
        // this.countDown();
      } else {
        this.dateTit = "倒计时结束";
        clearInterval(this.remTime);
      }
    },
    //定时器每一秒执行一次
    Time() {
      this.remTime = setInterval(() => {
        this.countDown();
      }, 1000);
    },

    // 多少月、天、时、分前
    gtePastTimesDate(time) {
      let startTime = new Date(time).getTime(); // 包含时间的日期字符串
      console.log(startTime);
      let nowTime = new Date(),
        month = 24 * 60 * 60 * 30 * 1000,
        Day = 24 * 60 * 60 * 1000,
        Hours = 60 * 60 * 1000,
        Minutes = 60 * 1000,
        diffMonth = parseInt((nowTime - startTime) / month),
        diffDay = parseInt((nowTime - startTime) / Day),
        diffHours = parseInt((nowTime - startTime) / Hours),
        diffMinutes = Math.floor((nowTime - startTime) / Minutes);
      if (diffMonth != 0 && diffMonth < 30) {
        return diffMonth + "月前";
      } else if (diffDay != 0 && diffDay < 7) {
        return diffDay + "天前";
      } else if (diffDay == 0 && diffHours != 0) {
        return diffHours + "小时前";
      } else if (diffDay == 0 && diffHours == 0 && diffMinutes != 0) {
        return diffMinutes + "分钟前";
      } else if (diffDay == 0 && diffHours == 0 && diffMinutes == 0) {
        return "刚刚";
      } else {
        return time;
      }
    },
  },
};
</script>

<style scoped>
.number {
  margin: 400px;
  font-size: 50px;
  color: red;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值