<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>
倒计时 / 多少月、天、时、分前
于 2022-03-30 20:46:33 首次发布