#countDown.js
前端框架:vue2.x
创建路径:src/utlis/countDwon.js
代码如下:
// 时间补0
const fillZero = n => n < 10 ? '0' + n : '' + n;
// 倒计时 time参数是日期 比如:2020-09-22 或者 2020.09.22
// type 是你想要的倒计时格式 DD:HH:MM:SS / xx天:xx时:xx分:xx秒
const countDown = (time, type) => {
if (!isNaN(+time)) time = +time;
//转换时间格式
if (typeof time === 'string') {
time = time.split('-').join('/');
time = time.split('.').join('/');
}
// 统一转换成时间戳 计算时间差
let delta = new Date(time).getTime() - Date.now();
if (delta <= 0) delta = 0;
// 常量表示几个常数
const DAY_MS = 24 * 60 * 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
const MINUTE_MS = 60 * 1000;
const SECOND_MS = 1000;
let days, hours, mins, secs;
switch (type) {
case 'DD:HH:MM:SS':
// 计算天数
days = Math.floor(delta / DAY_MS);
// 计算小时数
hours = Math.floor((delta - (days * DAY_MS)) / HOUR_MS);
// 计算分钟数
mins = Math.floor((delta - (days * DAY_MS) - (hours * HOUR_MS)) / MINUTE_MS);
// 计算秒数
secs = Math.floor((delta - (days * DAY_MS) - (hours * HOUR_MS) - (mins * MINUTE_MS)) / SECOND_MS);
break;
case 'HH:MM:SS':
// 计算小时数
hours = Math.floor(delta / HOUR_MS);
// 计算分钟数
mins = Math.floor((delta - (hours * HOUR_MS)) / MINUTE_MS);
// 计算秒数
secs = Math.floor((delta - (hours * HOUR_MS) - (mins * MINUTE_MS)) / SECOND_MS);
break;
case 'MM:SS':
// 计算分钟数
mins = Math.floor(delta / MINUTE_MS);
// 计算秒数
secs = Math.floor((delta - (mins * MINUTE_MS)) / SECOND_MS);
break;
case 'SS':
// 计算秒数
secs = Math.floor(delta / SECOND_MS);
break;
default:
// 计算小时数
hours = Math.floor(delta / HOUR_MS);
// 计算分钟数
mins = Math.floor((delta - (hours * HOUR_MS)) / MINUTE_MS);
// 计算秒数
secs = Math.floor((delta - (hours * HOUR_MS) - (mins * MINUTE_MS)) / SECOND_MS);
break;
}
// 拼接要显示的字符串
return {
days: fillZero(days),
hours: fillZero(hours),
mins: fillZero(mins),
secs: fillZero(secs)
};
};
export {
countDown
};
项目文件中使用:
<template>
<div class="home">
倒计时:{{ days }}天{{ hours }}:{{ mins }}:{{ secs }}
</div>
</template>
<script>
import { countDown } from '@/utils/countDwon'
export default {
data () {
return {
days: '',
hours: '',
mins: '',
secs: ''
}
},
created () {
setInterval(() => {
this.days = countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').days
? countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').days
: ''
this.hours = countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').hours
? countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').hours
: ''
this.mins = countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').mins
? (this.mins = countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').mins)
: ''
this.secs = countDown('2022-01-03 18:00:00', 'DD:HH:MM:SS').secs
}, 1000)
}
}
</script>
页面中效果: