假设有如下代码
var date = "2000-08-29"; console.log(new Date(date).getTime());
这段代码在安卓跟PC上都正常,但是在IOS上就没有结果了
IOS上只支持yyyy/MM/dd
这种标准格式
关于Date日期标准,截取 ECMA-262 standard 内容进行说明,如下:
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:
ECMAScript为基于ISO 8601扩展格式的日期时间定义了一个字符串交换格式。格式为YYYY-MM-DDTHH:mm:ss.sssZ,每个域的介绍如下:
- YYYY is the decimal digits of the year in the Gregorian calendar.
YYYY为格林威治时间年的十进制表达- “:” (hyphon) appears literally twice in the string.
“:”字面上出现在两个字符串之间- MM is the month of the year from 01 (January) to 12 (December).
MM表示月份从01(一月)到12(十二月)- DD is the day of the month from 01 to 31.
DD表示月份中的天数从01到31.- T “T” appears literally in the string, to indicate the beginning of the time element.
T字面上出现在字符串中,表明时间元素的开始- HH is the number of complete hours that have passed since midnight as two decimal digits.
HH表示从午夜算起,已经经过的完整两位小时数字- : “:” (colon) appears literally twice in the string.
“:”字出现在两个字符串之间- mm is the number of complete minutes since the start of the hour as two decimal digits.
mm表示从一个小时的开始算起,已经经过的完整两位分钟数字- ss is the number of complete seconds since the start of the minute as two decimal digits.
ss表示从一分钟的开始算起,已经经过的完整两位秒数数字- . “.” (dot) appears literally in the string.
“.”字面上出现在字符串里- sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the “.” and the milliseconds field may be omitted.
sss表示从一秒钟的开始算起,已经经过的完整毫秒数,用三位数表示。该域可忽略不写。- Z is the time zone offset specified as “Z” (for UTC) or either “+” or “-” followed by a time expression hh:mm
Z特指时区偏移(特指UTC)或使用跟随有时间表达式hh:mm 的”+”、”-“。如 +hh:mmThis format includes date-only forms:
这种格式可以只有日期,仅允许以下格式:
- YYYY
- YYYY-MM
- YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
这种格式也可以只有时间,仅允许以下格式:
- THH:mm
- THH:mm:ss
- THH:mm:ss.sss
Also included are “date-times” which may be any combination of the above.
<同时也可以包含以上提到的日期或时间的组合。
所以可以看到,问题在于YYYY-MM-DD格式是包含在标准中的,只是IOS没有实现。
解决方法:
如果需要替换的地方不多的话可以直接replace替换掉。
var newDate = new Date('2000-08-29'.replace(/-/g, "/"));
或者使用Moment.js这个库