<template>
<view class="page" :style="{color: fontColor}">
<view class="title" v-if="!isStart">
距离开始:
</view>
<view class="title" v-else>
距离结束:
</view>
<view class="days">
{{time.day || '00'}}天
</view>
<view class="hour">
{{time.hour || '00'}}时
</view>
<view class="minutes">
{{time.min || '00'}}分
</view>
<view class="security">
{{time.sec || '00'}}秒
</view>
</view>
</template>
<script>
export default {
data () {
return {
time: {},
isStart: false,
}
},
props: {
start_time: String,
end_time: String,
fontColor: String
},
mounted() {
this.countDown()
},
methods: {
timeFormat(param) {
return param < 10 ? '0' + param : param;
},
countDown () {
var interval = setInterval(() => {
// 当前时间
let nowTime = new Date().getTime();
let endTime = new Date((this.end_time.replace(/-/g,'/'))).getTime();
let startTime = new Date((this.start_time.replace(/-/g,'/'))).getTime();
// 已开始
if (startTime - nowTime < 0) {
this.isStart = true;
let time = (endTime - nowTime) / 1000;
let day = parseInt(time / (60*60*24));
let hour = parseInt(time % (60*60*24) / 3600);
let min = parseInt(time % (60*60*24) % 3600 / 60);
let sec = parseInt(time % (60*60*24) % 3600 %60);
this.time = {
day: this.timeFormat(day),
hour: this.timeFormat(hour),
min: this.timeFormat(min),
sec: this.timeFormat(sec)
}
} else if (startTime - nowTime > 0) { // 即将开始
this.isStart = false
let time = (startTime - nowTime) / 1000;
let day = parseInt(time / (60*60*24));
let hour = parseInt(time % (60*60*24) / 3600);
let min = parseInt(time % (60*60*24) % 3600 / 60);
let sec = parseInt(time % (60*60*24) % 3600 %60);
this.time = {
day: this.timeFormat(day),
hour: this.timeFormat(hour),
min: this.timeFormat(min),
sec: this.timeFormat(sec)
}
} else {
// 计时结束
clearInterval(interval)
}
}, 1000)
}
}
}
</script>
<style scoped lang="less">
.page {
width: 100%;
font-size: 24upx;
display: flex;
align-items: center;
.days,.title {
margin-right: 10upx;
}
}
</style>
计时开始则返回距离结束的时间;
计时还未开始则返回距离计时开始的时间;
调用
<TimeCount :start_time="start_time" :end_time="end_time" :fontColor="color"></TimeCount>
真机调试遇到的一个问题就是倒计时在Android / IOS 端无效,原因是App 端无法解析这种类型的时间格式“2019-12-10 12:20:00”,解决办法是将时间格式转为“2019/12/10 12:20:00”
使用正则表达式
.replace(/-/g,'/')
如果发现有问题的话请留言