效果图
倒计时,主要应用于活动倒计时
当前时间:2019-07-29 10:56:00
//时间传活动截止时间
const app = getApp();
Page({
data:{
currentTime:''
},
onLoad(){
app.countdown(this,'2019-07-30 10:20:00');
console.log(this.data.currentTime);
},
onUnload(){
//关闭页面时记得手动清除定时器
app.closeinterval();
}
})
//输出 0天23小时23分钟48秒
app.js
countdown(that, end_time) {
let app = this;
let EndTime = new Date(end_time);
EndTime = EndTime.getTime()
let NowTime = new Date().getTime();
let total_micro_second = EndTime - NowTime || [];
// 渲染倒计时时钟
that.setData({
currentTime: this.dateformat(total_micro_second)
});
if (total_micro_second <= 0) {
that.setData({
currentTime: "已经截止"
});
clearInterval(timer)
return;
}
timer = setTimeout(function() {
total_micro_second -= 1000;
app.countdown(that, end_time);
}, 1000)
},
//清除定时器
closeinterval() {
clearInterval(timer)
},
// 时间格式化输出,如11:03 25:19 每1s都会调用一次
dateformat(micro_second) {
//总秒数
var second = Math.floor(micro_second / 1000);
// 天数
var day = Math.floor(second / 3600 / 24);
// 小时
var hr = Math.floor(second / 3600 % 24);
//分钟
var min = Math.floor(second / 60 % 60);
// 秒
var sec = Math.floor(second % 60);
return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
},