<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,'/')
如果發現有問題的話請留言