JS 代码
// 传递过来的都是时间戳
function getResidueDate(start_date, end_date){
let residue = end_date - start_date;
let days = Math.floor(residue / 1000 / 60 / 60 / 24);
let hours = Math.floor((residue / 1000 / 60 / 60) % 24);
let minutes = Math.floor((residue / 1000 / 60) % 60);
let seconds = Math.floor((residue / 1000) % 60);
// 不需要补零的话,这部分就可以不用了
days = days < 10 ? "0" + days : days;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return `剩余:${days}天${hours}小时${minutes}分钟${seconds}秒`
}
VUE
<template>
<div>
剩余时间:
<p><span>天:</span>{{ days }}</p>
<p><span>时:</span>{{ hours }}</p>
<p><span>分:</span>{{ minutes }}</p>
<p><span>秒:</span>{{ seconds }}</p>
</div>
</template>
<script>
export default {
name: "Test",
data: function () {
return {
start_date: "2021-09-02 15:45:30", // 开始时间
end_date: new Date(), // 结束时间(时间戳)
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
};
},
computed: {
residue: function () {
return this.end_date - new Date(this.start_date).getTime();
},
},
created() {
this.getResidueDate();
},
methods: {
getResidueDate() {
this.days = this.addZero(
Math.floor(this.residue / 1000 / 60 / 60 / 24)
); //天
this.hours = this.addZero(
Math.floor((this.residue / 1000 / 60 / 60) % 24)
); //时
this.minutes = this.addZero(
Math.floor((this.residue / 1000 / 60) % 60)
); //分
this.seconds = this.addZero(Math.floor((this.residue / 1000) % 60)); //秒
},
addZero(d) {
return parseInt(d) < 10 ? "0" + d : d;
},
},
};
</script>