gpt4 book ai didi

IE9 中的 JavaScript 日期对象允许无效日期

转载 作者:行者123 更新时间:2023-11-29 18:27:04 26 4
gpt4 key购买 nike

当通过 JavaScript Date() 对象的构造函数传递无效日期时,IE9 似乎正在构造一个有效的日期,例如“2009 年 8 月 56 日”返回一个日期对象实例。相比之下,Chrome 则不然。

阅读了有关 IE9 中的 Date 对象的 MSDN 文档(下面的链接),其中有一段说明:

JavaScript is fairly flexible about the date format. It allows for variants such as 8-24-2009, August 24, 2009, and 24 Aug 2009. For more information, see Formatting Date and Time Strings (JavaScript).

以上段落摘自:http://msdn.microsoft.com/en-us/library/ee532932(v=vs.94).aspx

以下代码片段用于检查日期是否有效。它在 Chrome 中有效,但在 IE9 中无效:

function validateDate(d) {
var dt = new Date(d);
if (Object.prototype.toString.call(dt) !== "[object Date]") return false;

return !isNaN(dt.getTime());
}

运行这段代码时:

console.log(new Date("56 Aug 2009"));

IE9 结果

Fri Sep 25 00:00:00 UTC+0100 2009

Chrome 结果

Invalid Date

这是一个带有更详细示例的 JsFiddle:

http://jsfiddle.net/WKMdc/8/

这种行为是意外的(可能是由于不正确的假设,或者可能是验证中的错误未被注意到!)。

有什么替代方法可以验证日期是否有效,可以在 IE9 中使用并允许使用 native 浏览器功能?

最佳答案

正如 João 的回答中也指出的那样,问题是当通过构造函数创建新的 Date 对象时,浏览器将“帮助”通过执行存在差异的天数来“帮助”,例如29-Feb-2013 不是有效日期(2013 年 2 月只有 28 天)将变为 01-Mar-2013,或从原始日期起 + 1 天。

这不是很有帮助,因为在我的场景中我想将 29-Feb-2013 标记为用户无效条目。

尝试构建以下日期:

var parsedDate = new Date("29 Feb 2013");

为每个浏览器返回以下日期对象:

IE9 - Fri Mar 1 00:00:00 UTC 2013

Safari - Fri Mar 01 2013 00:00:00 GMT+0000 (GMT)

Chrome - Fri Mar 01 2013 00:00:00 GMT+0000 (GMT Standard Time)

具有“更不正确”日期的相同测试:

var parsedDate = new Date("32 Aug 2013");

为每个浏览器返回以下日期对象:

IE9 - Tue Sep 1 00:00:00 UTC+0100 2012

Safari - Invalid Date

Chrome - Invalid Date

NB IE 似乎更加宽松/灵活!

建议的解决方案只是检查解析的月份是否与预期的月份相同。如果没有,那么可以得出结论,日期添加已经发生并且应该抛出验证消息:

function dateIsValid(dateString) {

var month = dateString.split(" ")[1],
year = dateString.split(" ")[2];

var parsedDate = new Date(dateString);

// create a date object with the day defaulted to 01
var expectedMonth = new Date("01 " + month + " " + year);

// if the month was changed by the Date constructor we can deduce that the date is invalid!
if (parsedDate.getMonth() === expectedMonth.getMonth()) {
return true;
}

return false;
}

运行以下命令会在浏览器中产生一致的结果:

console.log(dateIsValid("01 Aug 2009")); // returns true
console.log(dateIsValid("56 Aug 2009")); // returns false
console.log(dateIsValid("29 Feb 2012")); // returns true
console.log(dateIsValid("29 Feb 2013")); // returns false

免责声明:这当然是一种解决方法。但它很简单,适用于我的场景!

关于IE9 中的 JavaScript 日期对象允许无效日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11956740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com