使用Date.parse确定有效日期 [英] Inconsistent determination of valid dates using Date.parse

查看:311
本文介绍了使用Date.parse确定有效日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试使用以下语法解析日期:

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

它将返回2013年3月1日。

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

将于2013年3月2日返回。但如果我执行

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

它将返回无效日期。我的观点是,为什么这些日期不是返回无效日期

解决方案

正确解析 Date.parse 的唯一格式是ISO 8601的简化。可以阅读有关 ecma规范的详细格式的详细信息, a>。



Date.parse 识别为日期的任何其他格式都是实现特定的。你提到的格式不是上述标准的一部分,所以每个实现都可以给出他们希望的任何结果。



发生这样的事情,当你通过什么样的一个月大于31的日子,解析器会认为它是一个无效的字符串,所以它将返回 NaN 。检查日期是否有效是因为月日不规则,闰年,缺少秒数,时区等各种问题而困难重重,因此将所有这些逻辑放在解析器中是不必要的。在日期显然有效的情况下,它被转换为时间戳,并由 Date.parse 返回,此时新的Date()可以使用。



结论是使用 Date.parse 的非标准格式是不可靠的,如果可能的话应该避免使用。


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?

解决方案

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.

这篇关于使用Date.parse确定有效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆