最近项目做一个答题活动, 需要所有用户统一时间并开始答题,
为了防止每个用户的时间不一样,所以需要从网络上获取时间,以此来校准
data() {
return {
countDownList: '00:00', // 倒计时时间
actEndTime: '2020-06-22 12:00:00', // 指定的时间
setTime: '' // 定时器
}
},
async getTT() {
// 请求获取网络时间
let res = await axios.getTime()
// res返回的是一个 字符串时间戳 1592795715393 所以需要转为时间对象
// console.log(new Date(parseInt(res, 10)).getTime() )
// 计算本地时间和 网络时间误差: 网络时间 - 本地时间
var num = new Date(parseInt(res, 10)).getTime() - new Date().getTime()
this.countDown(num)
},
// 倒计时函数
countDown(now) {
this.setTime = setInterval(() => {
// 获取当前时间,同时得到活动结束时间数组
let newTime = new Date().getTime();
// 对结束时间进行处理渲染到页面
// .replace(/\s/g,'T') 兼容safari 浏览器和ios , 他们没有其他浏览器的兼容功能 要接收 2020-06-22T12:00:00 的时间格式
let endTime = new Date(this.actEndTime.replace(/\s/g,'T')).getTime();
let obj = null;
// 如果活动未结束,对时间进行处理
if (endTime - newTime - now > 0) {
// 倒计时时间 = 结束时间 - (本地时间 + 时间误差)
let time = (endTime - newTime - now) / 1000;
// 获取天、时、分、秒
let day = parseInt(time / (60 * 60 * 24),10);
let hou = parseInt(time % (60 * 60 * 24) / 3600,10);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60,10);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60,10);
obj = {
day: this.timeFormat(day),
hou: this.timeFormat(hou),
min: this.timeFormat(min),
sec: this.timeFormat(sec)
};
} else { // 活动已结束,全部设置为'00'
obj = {
day: '00',
hou: '00',
min: '00',
sec: '00'
};
clearInterval(this.setTime);
}
// this.countDownList = obj.day +'天'+obj.hou+'时'+ obj.min + '分' + obj.sec + '秒';
this.countDownList = obj.min + ':' + obj.sec ;
}, 1000);
},
timeFormat(param) {
return param < 10 ? '0' + param : param;
}
这需要从后台获取服务器的当前时间, 需要后台给出一个接口