转载自:https://blog.youkuaiyun.com/m0_38082783/article/details/79851175
自己又经过了一些小调整,因为自己是小白,自己做个笔录,也希望能给其他小伙伴们一点帮助
wxml 文件
<view class='tui-countdown-content H90 flex-ct bt1' wx:for="{{countDownList}}" wx:key="countDownList">
<view wx:if='{{item.status}}'>
<text>剩余</text>
<text>{{item.day}}</text>天
<text>{{item.hou}}</text>时
<text>{{item.min}}</text>分
<text>{{item.sec}}</text>秒
</view>
<view wx:else>活动已结束,敬请期待新的活动</view>
</view>
.js文件
const countDown = require('../../utils/countDown.js')
Page({
data: {
//倒计时
countDownList: [] //倒计时时间组
, actEndTimeList: ['2019-08-24 10:00:43', '2019-08-24 11:00:00', '2019-08-20 11:00:00'] //结束时间组
},
onLoad() {
let that =this
that.countDown();// 执行倒计时函数
},
//倒计时函数
countDown() {
let that = this
countDown.countDown(that, that.data.actEndTimeList)
setTimeout(that.countDown, 1000);
}
})
countDown.js 文件
//小于10的格式化函数
function timeFormat(param) {//小于10的格式化函数
return param < 10 ? '0' + param : param;
}
//日期改为时间戳(时分秒)
function dateNum(date) {
date = date.substring(0, 19);
date = date.replace(/-/g, '/');
var timestamp = new Date(date).getTime();
return timestamp
}
//倒计时函数
function countDown(_that, endTimeList) {
// 获取当前时间,同时得到活动结束时间数组
let newTime = new Date().getTime();
let countDownArr = [];
var len = endTimeList.length
// 对结束时间进行处理渲染到页面
for (let i = 0; i < len;i++){
let endTime = dateNum(endTimeList[i])
let obj = null;
// 如果活动未结束,对时间进行处理
if (endTime - newTime > 0) {
let time = (endTime - newTime) / 1000;
// 获取天、时、分、秒
let day = parseInt(time / (60 * 60 * 24));
let hou = parseInt(time % (60 * 60 * 24) / 3600);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
obj = {
day: timeFormat(day),
hou: timeFormat(hou),
min: timeFormat(min),
sec: timeFormat(sec),
status:true //活动状态进行中
}
} else {//活动已结束,全部设置为'00'
obj = {
day: '00',
hou: '00',
min: '00',
sec: '00',
status: false //活动状态已结束
}
}
countDownArr.push(obj);
}
// 渲染,然后每隔一秒执行一次倒计时函数
_that.setData({ countDownList: countDownArr })
}
module.exports = {
countDown: countDown //倒计时函数
}