<div id="app">{{ `${hr}:${min}:${sec}` }}</div>
<script>
let app = new Vue({
el: '#app',
data: {
day: 0, hr: 0, min: 0, sec: 0
},
mounted: function () {
this.countdown()
},
methods: {
countdown: function () {
const end = Date.parse(new Date('2019-11-12 16:00:00'))
const now = Date.parse(new Date())
const msec = end - now
let day = parseInt(msec / 1000 / 60 / 60 / 24)
let hr = parseInt(msec / 1000 / 60 / 60 % 24)
let min = parseInt(msec / 1000 / 60 % 60)
let sec = parseInt(msec / 1000 % 60)
this.day = day
this.hr = hr > 9 ? hr : '0' + hr
this.min = min > 9 ? min : '0' + min
this.sec = sec > 9 ? sec : '0' + sec
const that = this
setTimeout(function () {
that.countdown()
}, 1000)
}
}
})
</script>
msec 是当前时间距目标时间的毫秒数,由时间戳相减得到,我们将以这个数为基础计算。我们都知道1天等于24小时,1小时等于60分钟,1分钟等于60秒,1秒等于1000毫秒。所以,msec / 1000 / 60 / 60 / 24 保留整数就是天数。如果换用 % 取余数,再保留整数后得到的就是小时数。以此类推就能算出其他所有数
function countdown () {
// 目标日期时间戳
const end = Date.parse(new Date('2019-12-01'))
// 当前时间戳
const now = Date.parse(new Date())
// 相差的毫秒数
const msec = end - now
// 计算时分秒数
let day = parseInt(msec / 1000 / 60 / 60 / 24)
let hr = parseInt(msec / 1000 / 60 / 60 % 24)
let min = parseInt(msec / 1000 / 60 % 60)
let sec = parseInt(msec / 1000 % 60)
// 个位数前补零
hr = hr > 9 ? hr : '0' + hr
min = min > 9 ? min : '0' + min
sec = sec > 9 ? sec : '0' + sec
// 控制台打印
console.log(`${day}天 ${hr}小时 ${min}分钟 ${sec}秒`)
// 一秒后递归
setTimeout(function () {
countdown()
}, 1000)
}