微信小程序设置倒计时第二版

第一版时有发版,使用的是第三方插件,但是使用时需求不够满足并且功能不够完善有问题,所以进行第二版倒计时开发,没使用插件,下面时使用逻辑和代码
1.定义获取时间函数,并获取到后台传来的当前系统时间,并没有自动获取到手机时间,是因为担心每个人手机的时间不一样,但是考试结束时间一样,就通过后台来获取保持一致
2.需要用到两个时间,当前的时间和结束的时间,通过转换为当前国际标准时间,这里设置的公共方法
//转换时间为中国标准时间const setTime = (startTime,endTime,curTime) =>{letcurrent ,//当前时间startTime1 ,//考试开始时间endTime1 = ""; //考试结束时间let cur = curTime.replace(/\-/g, "/")//获取当前时间let start = startTimelet end = endTimelet start1 = start.replace(/\-/g, "/")let end1 = end.replace(/\-/g, "/")current = new Date(cur)startTime1= new Date(start1)endTime1= new Date(end1)console.log(current)//Tue Jun 08 2021 10:41:33 GMT+0800 (中国标准时间)let obj={currentTime:current,endTime:endTime1,startTime:startTime1}return obj}

微信小程序设置倒计时第二版

文章插图
3.将转换后的值带入到倒计时方法中
let obj = setTime(wx.getStorageSync('startTime'), wx.getStorageSync('endTime'), res.data)let {currentTime} = objlet {endTime} = objlet {startTime} = obj//这里设置6分钟的倒计时,是为了以防中途退出,时间不准确,从新校验时间setTimeout(function () {that.getTime()},1*60*1000);if(!that.data.currentTime) {this.setData({currentTime: new Date(currentTime).getTime()})that.countDown(new Date(endTime).getTime())} else{this.setData({currentTime: new Date(currentTime).getTime()})} }
4.开始倒计时
//考试结束倒计时方法countDown(endTime) {let that = thislet surplus = ""let timer =setInterval(function() {let currentTime = that.data.currentTimelet mss = endTime - currentTime//先计算结束时间减去当前时间currentTime = currentTime+ 1000that.setData({currentTime: currentTime})// let mss =10 //先计算结束时间减去当前时间if(mss <=0){let {saveStateOver} = that.data//当saveStateOver不为false时,结束给出交卷提示并自动交卷if(saveStateOver){that.setData({show1: true})}//倒计时结束,清除定时器clearTimeout(timer)timer = nullsetTimeout(function () {that.setData({show1: false})//倒计时到了触发交卷that.onClose()}, 5000);}//toString().length下面方法适当时/分/秒为个位数时前面补0为00:00...显示效果更好var days = parseInt(mss / (1000 * 60 * 60 * 24));var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));if(hours.toString().length < 2){hours = "0"+hours}var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));if(minutes.toString().length < 2){minutes = "0"+minutes}var seconds =parseInt((mss % (1000 * 60)) / 1000);if(seconds.toString().length < 2){seconds = "0"+seconds}if( days ==0){surplus =hours + ":" + minutes + ":" + seconds; //计算剩余时间}else{surplus =days + ":"+ hours + ":" + minutes + ":" + seconds; //计算剩余时间}//surplus将倒计时输出到页面that.setData({timesOver:surplus})//设置1s}, 1000)},
【微信小程序设置倒计时第二版】效果如图