微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 为什么2/8888/2016是IE和Firefox中的有效日期?

如果您采取以下措施:
var s = "2/8888/2016";
var d = new Date(s);
alert(d);

在Chrome中,您将获得:

Invalid Date

但在IE和Firefox中,你会得到:

Fri Jun 01 2040 00:00:00 GMT-0500 (Central Daylight Time)

它似乎只是在2月01日加入了8888天.相反,我希望这个日期被视为无效.有没有办法让FireFox和IE认为这个日期字符串无效?

解决方法

简短回答:

这是你提到的浏览器的错误行为.

您必须自己检查日期格式是否正确.但这很简单,我建议采用这种方法

拆分年y,月m,日d中的日期并创建Date对象:

var date = new Date( y,m - 1,d ); // note that month is 0 based

然后将原始值与使用Date方法获得的逻辑值进行比较:

var isValid = date.getDate() == d &&
              date.getMonth() == m-1 &&
              date.getFullYear() == y;

在执行所有这些操作之前,您可能需要检查日期字符串是否对任何浏览器有效:

Detecting an “invalid date” Date instance in JavaScript

答案很长:

Firefox(和IE)接受“2/8888/2016”作为正确的字符串状态格式似乎是一个错误/错误行为.

事实上,根据ECMAScript 2015语言规范,当使用单个字符串参数调用Date()时,其行为应与Date.parse()相同

http://www.ecma-international.org/ecma-262/6.0/#sec-date-value

后者

attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16)

..这里指定的

http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

在哪里可以阅读

The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

[…]

MM is the month of the year from 01 (January) to 12 (December).

DD is the day of the month from 01 to 31.

似乎Firefox正在解释字符串值,就像使用多个参数调用Date()时一样.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Note: Where Date is called as a constructor with more than one argument,if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value),the adjacent value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new Date(2014,1,1),both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013,2,70) is equivalent to new Date(2013,10) which both create a date for 2013-03-01T01:10:00.

这可以解释“2/8888/2016”如何变成2040-05-31T22:00:00.000Z

原文地址:https://www.jb51.cc/js/157070.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐