时间转换(已使用时间计时&&秒转时分秒格式)

一、时间戳转时分秒

// 计算已使用时间
    jishiqi() {
      let kaishishijian = new Date('2020-10-22 12:00:00').getTime() //--改变
      this.useTime = this.formatDuring(new Date().getTime() - kaishishijian)
      let that = this 
      this.timeId = setInterval(() => {
           that.useTime = that.formatDuring(new Date().getTime() - kaishishijian)
           console.log('123')
         }, 1000)
    },
// 将时间戳转化为时分秒格式
    formatDuring(mss) {
      var hours = Math.floor(mss / (1000 * 60 * 60))
      var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60))
      var seconds = Math.floor((mss % (1000 * 60)) / 1000)
      hours = hours < 10 ? '0' + hours : hours
      minutes = minutes < 10 ? '0' + minutes : minutes
      seconds = seconds < 10 && seconds >= 1 ? '0' + seconds : seconds
      return hours + ' :' + minutes + ' :' + seconds
    },

  //   监听状态变化,如果状态为开启则开始定时,状态为关闭则清除定时器
  watch: {
    zhuangtai: {
      handler() {
        if (this.zhuangtai) {
          this.jishiqi()
        } else {
          clearInterval(this.timeId)
        }
      },
      immediate: true,
    },
  },

二、毫秒转时分秒

  data(){
      return{
        s:5000, //秒数
        timeId:null,
        useTime:'',//转换后的时间
    }  
  }
  ......
  // 计算已使用时间
  jishiqi() {
      this.formatDuring()
      this.timeId = setInterval(() => {
        this.s += 1
        this.formatDuring()
      }, 1000)
    },
  },
  // 时间转化
  formatDuring(){
    let t
    let s = this.s//秒数
    if (s > -1) {
        let hour = Math.floor(s / 3600)
        let min = Math.floor(s / 60) % 60
        let sec = s % 60
        if (hour < 10) {
            t = '0' + hour + ':'
        } else {
            t = hour + ':'
        }
        if (min < 10) {
            t += '0'
        }
        t += min + ':'
        if (sec < 10) {
            t += '0'
        }
        t += sec
      }
      this.useTime = t
    },
  //   监听状态变化,如果状态为开启则开始定时,状态为关闭则清除定时器
  watch: {
    zhuangtai: {
      handler() {
        if (this.zhuangtai) {
          this.jishiqi()
        } else {
          clearInterval(this.timeId)
        }
      },
      immediate: true,
    },
  },

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值