一、时间戳转时分秒
// 计算已使用时间
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,
},
},