今天在测试的时候发现,在Chrome中的以下代码:git
new Date("2014-03-09");
在Safari中报错invalid date。通过查阅资料找到相似的问答:express
stackOverflow地址:http://stackoverflow.com/questions/4310953/invalid-date-in-safariapp
解释与翻译以下:测试
目前Safari能够支持的标准格式以下:spa
DateJS 是一个很好的格式化非标准格式日期的库。翻译
关于Date日期标准,原文截取 ECMA-262 standard 内容进行说明,引文以下:code
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:orm
ECMAScript为基于ISO 8601扩展格式的日期时间定义了一个字符串交换格式。格式为YYYY-MM-DDTHH:mm:ss.sssZ,每一个域的介绍以下:htm
- 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:mm
This format includes date-only forms: 这种格式能够只有日期,仅容许如下格式:blog
- 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没有实现。可使用上文提到的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");
不过,若是仅是不多量的使用日期时间,我的认为无需打动干戈的去使用DateJS这种库,简单的进行正则匹配为safari能够识别的格式便可,以下:
new Date('2011-04-12'.replace(/-/g, "/"))
更多其余的变化,能够根据本身的业务需求进行代码上的调整。