问题出现在本人开发uniapp H5页面时有需要一个本日剩余时间倒计时的功能,方法如下:
onLoad(option) {
clearInterval(this.countdownTimer); //进来前先清除一遍定时器
this.setTimer();
},
destroyed: function() {
// 每次离开当前界面时,清除定时器
clearInterval(this.countdownTimer)
this.countdownTimer = null;
},
methods:{
setTimer() {
if (this.countdownTimer == null) {
this.countdownTimer = setInterval(() => {
this.countdown();
}, 1000)
}
},
countdown() {
let date = new Date();
const yearNow = date.getFullYear();
const monthNow = Number(date.getMonth()) + 1;
const dayNow = date.getDate();
let end = yearNow + "-" + monthNow + "-" + dayNow + " " + "23:59:59";
end = new Date((end)).getTime();
let start = new Date().getTime();
let surplus = (end - start).toFixed(0); //剩余毫秒数
let hours = parseInt(surplus / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
let minutes = parseInt(surplus / 1000 / 60 % 60, 10); //计算剩余的分钟
let seconds = parseInt(surplus / 1000 % 60, 10); //计算剩余的秒数
String(hours).length == 1 ? this.hours = "0" + String(hours) : this.hours = String(hours);
String(minutes).length == 1 ? this.minutes = "0" + String(minutes) : this.minutes = String(minutes);
String(seconds).length == 1 ? this.seconds = "0" + String(seconds) : this.seconds = String(seconds);
},
}
但是测试阶段发现了一个问题 Android端可以正常显示倒计时
但是到了ios端就会成为 NAN 时 NAN 分 NAN 秒 ;
问题解决方法:
end = new Date((end).replace(/-/g,'/')).getTime();
let start = (date.replace(/-/g,'/')).getTime();
xxx.replace(/-/g,'/')*兼容Android和ios都能快速解决