苹果手机和安卓手机对于new Date()处理的一个小bug
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| alert(new Date('2019-02-14')) alert(new Date('2019-02-14'))
alert(new Date('2019-02-14 11:00:05')) alert(new Date('2019-02-14 11:00:05'))
alert(new Date('2019-02-14 11:00:05.0')) alert(new Date('2019-02-14 11:00:05.0'))
alert(new Date('2019/02/14')) alert(new Date('2019/02/14'))
alert(new Date('2019/02/14 11:00:05')) alert(new Date('2019/02/14 11:00:05'))
alert(new Date('2019/02/14 11:00:05.0')) alert(new Date('2019/02/14 11:00:05.0'))
|
可以看到,对于格式化yyyy-mm-dd
格式,苹果和安卓的结果都是正常的,而只要日期后面加上时分秒苹果就会输出异常。
而对于yyyy/mm/dd
格式,不管加不加时分秒,苹果和安卓都是正常,但是加上毫秒(因为有些数据库的时间格式默认到了毫秒)后苹果又会异常。
解决方案
对于没有精确到毫秒的时间使用正则替换“-”为“/”
1 2 3
| function formatIOS(date) { retuen new Date(date.replace(/-/g, "/")) }
|
对于精确到了毫秒的时间只能舍弃毫秒而截取前面19位了
1 2 3
| function formatIOS(date) { retuen date.substr(0, 19) }
|