微信小程序时间bug
近日做日历组件,需要大量的时间计算
手机iphone ios 13
模拟器版本1.9.0
原代码
let date = '2019-10-5'
let dateObj = new Date(date)
let timestamp = dateObj.getTime()
以上代码在pc模拟器和真机模拟可以正常,但预览模式用手机一篇空白,经调试定位new Date(...)
方法在预览模式出错,得出值为NaN
.
定位到问题后,分别尝试以下方法
1. new Date('2019-10-5') //出错输出
2. new Date('2019-10-05') // 正确输出
3. new Date('2019/10/5') //正确输出
4. new Date('2019:10:5') // 错误输出
经过上几轮测试,决定使用第三种方法来定制一个兼容方法,
function newDate(timepoint){
if (timepoint) {
if (timepoint.getDate && timepoint.getFullYear) return timepoint
if (lib.isNumber(timepoint)) {
return new Date(timepoint)
}
if (lib.isString(timepoint)) {
timepoint = timepoint.replace(/\-/g, '/')
timepoint = timepoint.replace(/\:/g, '/')
return new Date(timepoint)
}
} else {
return new Date()
}
}