Inconsistent determination of valid dates using Da

2019-06-17 04:53发布

If I try to parse a date with this syntax:

var date1 = new Date(Date.parse('2013' + '/' + '02' + '/' + '29'));

it will return 1 March 2013.

var date1 = new Date(Date.parse('2013' + '/' + '02' + '/' + '30'));

it will return 2 March 2013. But if I do

var date1 = new Date(Date.parse('2013' + '/' + '02' + '/' + '33'));

it will return Invalid Date.

My point is, why don't all of these dates return Invalid Date?

3条回答
你好瞎i
2楼-- · 2019-06-17 05:05

The only format that Date.parse is required to parse correctly is a simplification of ISO 8601. You can read more details about the exact format in the ecma specification.

Any other format that Date.parse recognizes as a date is implementation specific. The format you mentioned is not part of the standard above, so each implementation can give whatever result for it they wish.

It so happens that when you pass in what looks like a day of the month larger than 31, the parser will consider it to be an invalid string, so it will return NaN. Checking to see if the date is valid is a lot more difficult due to various issues with month-day irregularities, leap years, missing seconds, timezones, etc, so placing all of that logic in the parser is not warranted. With the date apparently valid, it is converted to a timestamp and returned by Date.parse and at that point new Date() has something to work with.

The conclusion is that using non-standard formats with Date.parse is unreliable and should be avoided if possible.

查看更多
Explosion°爆炸
3楼-- · 2019-06-17 05:12

Terrible design perhaps? (or rather dodgy implementation of the standards)

There's always issues when working with the JavaScript date object esp cross browser (the browser guys tend to implement the standards in their own way). I can keep you busy for a while with horror stories/issues I've encountered over the years - thats why we've got nice libraries like DateJs.

E.g this (your example) isn't even the behavior for ALL browsers, tested it in IE9 and the last snippet returns 5 Mar 2013 (like expected from the the other two preceding snippets), in Chrome the last snippet returns an invalid date.

But yes, I would agree that at would have made more sense if all three returned invalid dates.

Update(2015/1/8)

It seems like DateJs is no longer really actively being maintained? You guys might rather want to look into using MomentJs as an alternative.

查看更多
可以哭但决不认输i
4楼-- · 2019-06-17 05:13

Because values for day can hold up to number 31.

查看更多
登录 后发表回答