alert(new Date('2010-11-29'));
Chrome, ff在这方面没有问题,但safari会喊“无效日期”。为什么?
编辑:好的,根据下面的评论,我使用了字符串解析,并尝试了这个:
alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari
编辑2018年3月22日:似乎人们仍然在这里着陆-今天,我会使用moment或date-fns,然后就不用了。Date-fns是非常痛苦的,而且很轻。
模式yyyy-MM-dd并不是Date构造函数的官方支持格式。Firefox似乎支持它,但别指望其他浏览器也能这么做。
下面是一些受支持的字符串:
;
yyyy / MM / dd
MM / dd / yyyy
MMMM dd, yyyy
MMM dd, yyyy
DateJS似乎是解析非标准日期格式的一个很好的库。
编辑:刚刚检查了ECMA-262标准。引自15.9.1.15节:
日期时间字符串格式
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.
"-" (hyphon) appears literally twice in the string.
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" 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
它还包括只有时间的表单
附加一个可选的时区偏移量:
THH:毫米
THH: mm: ss
THH: mm: ss.sss
还包括“约会时间”
可以是上述的任何组合。
所以,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");
要让解决方案在大多数浏览器上都能工作,您应该使用这种格式创建日期对象
(year, month, date, hours, minutes, seconds, ms)
例如:
dateObj = new Date(2014, 6, 25); //UTC time / Months are mapped from 0 to 11
alert(dateObj.getTime()); //gives back timestamp in ms
工作良好的IE, FF, Chrome和Safari。甚至是更老的版本。
IE开发中心:日期对象(JavaScript)
Mozilla Dev Network:日期