报错代码
new Date("2016-04-05 11:11:11");//在Safari中报错invalid date
原因
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:
- YYYY is the decimal digits of the year in the Gregorian calendar.
MM is the month of the year from 01 (January) to 12 (December).
DD is the day of the month from 01 to 31.
T “T” appears literally in the string, to indicate the beginning of the time element.
HH is the number of complete hours that have passed since midnight as two decimal digits.
- : “:” (colon) appears literally twice in the string.
- mm is the number of complete minutes since the start of the hour as two decimal digits.
- ss is the number of complete seconds since the start of the minute as two decimal digits.
- . “.” (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.
Z is the time zone offset specified as “Z” (for UTC) or either “+” or “-” followed by a time expression hh:mm
This 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格式是包含在标准中的,只是Safari没有实现。
目前Safari5支持的格式
MM-dd-yyyy yyyy/MM/dd MM/dd/yyyy MMMM dd, yyyy MMM dd, yyyy
解决办法
使用DateJS (DateJS 是一个很好的格式化非标准格式日期的库);
var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
如果日期量少,代码不复杂可以选择把-替换掉
new Date('2011-04-12'.replace(/-/g, "/"))