微信小程序切图之天、时、分、秒倒计时实现代码,亲测有用!
视图
<!-- index.wxml -->
<view class='datetimeTo'>距离:<text style='color:blue'>{{datetimeTo}}</text></view>
<view class='timeLeft'>还有:<text style='color:red'>{{timeLeft}}</text></view>
2、逻辑
//index.js
const util = require('../../utils/util.js')
Page({
data: {
datetimeTo: "2019/01/01 10:30:00 GMT+0800", // 秒杀开始时间
timeLeft: "" // 剩下的时间(天时分秒)
},
onShow: function () {
this.data.timer = setInterval(() =>{ //注意箭头函数!!
this.setData({
timeLeft: util.getTimeLeft(this.data.datetimeTo)//使用了util.getTimeLeft
});
if (this.data.timeLeft == "0天0时0分0秒") {
clearInterval(this.data.timer);
}
}, 1000);
}
});
3、工具
//util.js
//取倒计时(天时分秒)
function getTimeLeft(datetimeTo){
// 计算目标与现在时间差(毫秒)
let time1 = new Date(datetimeTo).getTime();
let time2 = new Date().getTime();
let mss = time1 - time2;
// 将时间差(毫秒)格式为:天时分秒
let days = parseInt(mss / (1000 * 60 * 60 * 24));
let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
let seconds = parseInt((mss % (1000 * 60)) / 1000);
return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
}
module.exports = {
getTimeLeft: getTimeLeft
}
本文由专业的WEB前端外包公司-切图网原创,转载请保留版权( WEB前端开发外包www.qietu.com )切图网始于2007年,提供高品质的前端开发服务、前端外包、切图外包。欢迎来电咨询!热线:027-81777732、13343477732
标签:微信小程序