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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...