这是我项目中的例子,如果有更好的建议欢迎留言 ,一起学习
//获取时间
var sekillStartTime = resultLis[0].planGroup0.sekillStartTime;//开始时间
var sekillEndTime = resultLis[0].planGroup0.sekillEndTime;//结束时间
// 开始时间的总秒数ps:这里var的话是页面传的值的名字也是sekillStartTime这个
var startTimetm = "20" + sekillStartTime.substring(0, 2) + "-" + sekillStartTime.substring(2, 4) + "-" + sekillStartTime.substring(4, 6) + " " + sekillStartTime.substring(6, 8) + ":" + sekillStartTime.substring(8, 10) + ":" + sekillStartTime.substring(10, 12);
var startDate = new Date(startTimetm).getTime();
// 结束时间的总秒数
sekillEndTime = "20" + sekillEndTime.substring(0, 2) + "-" + sekillEndTime.substring(2, 4) + "-" + sekillEndTime.substring(4, 6) + " " + sekillEndTime.substring(6, 8) + ":" + sekillEndTime.substring(8, 10) + ":" + sekillEndTime.substring(10, 12);
var endTDate = new Date(sekillEndTime).getTime();
//秒抢的开始时间
var newTime = sekillStartTime.substring(6, 8) + ":" + sekillStartTime.substring(8, 10) + ':' + sekillStartTime.substring(10, 12);
//获取系统当前时间
var currentDate = new Date();
currentDate= currentDate.getTime()
//时间段要注意两种情况一种是刚进来就已经开始倒计时,还有就是到页面还没有倒计时,就用结束的时间减去当前的时间
var totalSecond ;
//秒抢开始时间减去当前时间就是当前时间到开始倒计时之间的时间段
var startSecond = startDate - currentDate;
// console.log(startSecond)
if (message == 1){ //倒计时状态
if (startSecond<0){//已经在倒计时了
totalSecond = parseInt((endTDate - currentDate) / 1000);
} else if (startSecond > 0){//还没有倒计时
totalSecond = parseInt((endTDate - startDate) / 1000);
}
var howmany = parseInt(startSecond / 1000);//当前时间到开始倒计时之间的时间段
that.countdown(howmany)
setTimeout(function () {
that.countdown(totalSecond)
}, startSecond)
} else if (message == 2){//今天秒抢场次结束
that.setData({
linguisticShow: false,
})
}
// 倒计时方法
countdown: function (totalSecond){
var that=this;
var interval = setInterval(function () {
console.log('i')
// 总秒数
var second = totalSecond;
// 天数位
var day = Math.floor(second / 3600 / 24);
var dayStr = day.toString();
if (dayStr.length == 1) dayStr = '0' + dayStr;
// 小时位
var hr = Math.floor((second - day * 3600 * 24) / 3600);
var hrStr = hr.toString();
if (hrStr.length == 1) hrStr = '0' + hrStr;
// 分钟位
var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
var minStr = min.toString();
if (minStr.length == 1) minStr = '0' + minStr;
// 秒位
var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;;
var secStr = sec.toString();
if (secStr.length == 1) secStr = '0' + secStr;
that.setData({
countDownHour: hrStr,
countDownMinute: minStr,
countDownSecond: secStr,
});
totalSecond--;
if (totalSecond < 0) {
this.setData({
countDownHour: '00',
countDownMinute: '00',
countDownSecond: '00',
});
}
}.bind(that), 1000);
},