JavaScript 中 new Date(time).getTime() 获取时间戳方法在 iOS 中的兼容性问题

在 iOS 系统的 H5 页面中获取时间戳方法new Date(time).getTime()存在返回 NaN 或结果不准确的情况

在 iPhone 8 中 iOS 11.03 系统下的 H5 页面测试new Date(time).getTime()方法

测试代码:

 

 测试结果:

 

由上图可知,第 1、2、4 种方式获取的结果为 NaN,第 3 种获取的结果不准确,使用第 5、6 种日期格式获取时间戳的兼容性最好。

解决获取时间戳方法new Date(time).getTime()在 iOS 中的兼容性问题方法

解决方法:使用time.replace(/\-/g, "/")转换日期格式(转换为2018/11/12 00:00:00格式),再通过new Date(newTime).getTime()获取时间戳。如:

const time = "2023-04-14 16:42:30",
  newTime = time.replace(/\-/g, "/");
console.log(new Date(newTime).getTime());

// console.log(new Date("2023-04-14 16:42:30".replace(/\-/g, '/')).getTime());

猜你喜欢

转载自blog.csdn.net/lwf3115841/article/details/130162013