vue 实现两个时间戳 相减得到一个倒计时
<template>
<div> 距离结束还剩 {{ formattedTime }} </div> </template>
<script>
export default {
data() {
return {
endTime: new Date('2029-07-17T00:00:00').getTime(), // 结束时间的时间戳
currentTime: Date.now(), // 当前时间的时间戳
countdownInterval: null,
formattedTime: '',
};
},
computed: {
},
methods: {
startCountdown() {
this.countdownInterval = setInterval(() => {
this.currentTime+= 1000;
const timeRemaining = this.endTime - this.currentTime;
if (timeRemaining <= 0) {
clearInterval(this.countdownInterval);
this.formattedTime = '已结束';
} else {
this.updateFormattedTime(timeRemaining);
}
}, 1000);
},
updateFormattedTime(timeRemaining) {
const seconds = Math.floor((timeRemaining / 1000) % 60);
const minutes = Math.floor((timeRemaining / 1000 / 60) % 60);
const hours = Math.floor((timeRemaining / (1000 * 60 * 60)) % 24);
const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
this.formattedTime = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
},
},
created() {
},
mounted(){
this.startCountdown();
},
};
</script>