苹果手机和安卓手机对于new Date()处理的一个小bug

First Post:

Last Update:

苹果手机和安卓手机对于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'))  //iphone:  Thu Feb 14 2019 08:00:00 GMT+0800(CST)
alert(new Date('2019-02-14')) //Android: Thu Feb 14 2019 08:00:00 GMT+0800(CST)

alert(new Date('2019-02-14 11:00:05')) //iphone: Invalid Date
alert(new Date('2019-02-14 11:00:05')) //Android: Thu Feb 14 2019 11:00:05 GMT+0800(CST)

alert(new Date('2019-02-14 11:00:05.0')) //iphone: Invalid Date
alert(new Date('2019-02-14 11:00:05.0')) //Android: Thu Feb 14 2019 11:00:05 GMT+0800(CST)

alert(new Date('2019/02/14')) //iphone: Thu Feb 14 2019 08:00:00 GMT+0800(CST)
alert(new Date('2019/02/14')) //Android: Thu Feb 14 2019 08:00:00 GMT+0800(CST)

alert(new Date('2019/02/14 11:00:05')) //iphone: Thu Feb 14 2019 11:00:05 GMT+0800(CST)
alert(new Date('2019/02/14 11:00:05')) //Android: Thu Feb 14 2019 11:00:05 GMT+0800(CST)

alert(new Date('2019/02/14 11:00:05.0')) //iphone: Invalid Date
alert(new Date('2019/02/14 11:00:05.0')) //Android: Thu Feb 14 2019 11:00:05 GMT+0800(CST)

可以看到,对于格式化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)
}