使用new Date在计算时间过程中兼容性问题

115 阅读1分钟

问题:new Date('2024-09-11').getTime(),在ios系统获取值为NaN,但是在安卓可以正确获取

在ios系统中,时间格式为2024-09-11,系统不能识别-,但是确可以识别 /

let expDate1 = new Date('2024-09-11')     
let expDate2 = new Date('2024/09/11')
let curDate1 = new Date()
console.log(expDate1,'expDate1')
console.log(curDate1,'curDate1')
console.log(expDate2,'curDate2')
console.log(expDate1.getTime(),'date获取横线拼接')
console.log(curDate1.getTime(),'curDate1-date')
console.log(expDate2.getTime(),'curDate2-date')

ios真机打印:

image.png 安卓机真机打印:

image.png

解决办法:将时间拼接由‘-’,替换成‘/’

let time ="2024-09-11"
let aa = new Date(time.replace(/-/g,'/')).getTime()

不同的浏览器和系统对日期字符串的解析规则也可能有所不同,这可能导致在某些特定环境下,即使日期字符串的格式看似正确,也可能出现解析错误。因此,为了保证代码的兼容性和稳定性,开发者在处理日期时应该考虑到这些潜在的兼容性问题,并采取相应的措施来避免这些问题。