我想知道JS中有效日期对象和无效日期对象之间的区别,但无法弄清楚:
var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
编写isValidDate函数有什么想法吗?
Ash建议使用Date.parse来解析日期字符串,这提供了一种权威的方法来检查日期字符串是否有效。如果可能的话,我更希望我的API接受Date实例,并能够检查/断言它是否有效。Borgar的解决方案做到了这一点,但我需要在浏览器上进行测试。我还想知道是否有更优雅的方式。Ash让我考虑不让我的API接受Date实例,这是最容易验证的。Borgar建议测试Date实例,然后测试Date的时间值。如果日期无效,则时间值为NaN。我用ECMA-262检查了一下,这种行为符合标准,这正是我所要的。
选择的答案很好,我也在使用它。然而,如果您正在寻找一种验证用户日期输入的方法,您应该知道date对象非常持久地将看似无效的构造参数转换为有效的构造参数。以下单元测试代码说明了这一点:
QUnit.test( "valid date test", function( assert ) {
//The following are counter-examples showing how the Date object will
//wrangle several 'bad' dates into a valid date anyway
assert.equal(isValidDate(new Date(1980, 12, 15)), true);
d = new Date();
d.setFullYear(1980);
d.setMonth(1);
d.setDate(33);
assert.equal(isValidDate(d), true);
assert.equal(isValidDate(new Date(1980, 100, 150)), true);
//If you go to this exterme, then the checker will fail
assert.equal(isValidDate(new Date("This is junk")), false);
//This is a valid date string
assert.equal(isValidDate(new Date("November 17, 1989")), true);
//but is this?
assert.equal(isValidDate(new Date("November 35, 1989")), false);
//Ha! It's not. So, the secret to working with this version of
//isValidDate is to pass in dates as text strings... Hooboy
//alert(d.toString());
});
我会这样做:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}
更新〔2018-05-31〕:如果您不关心来自其他JS上下文(外部窗口、框架或iframe)的Date对象,则可以使用更简单的形式:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
更新[2021-02-01]:请注意,“无效日期”(2013-13-32)和“无效日期对象”(new date('fo'))之间存在根本区别。只有当date实例有效时,此答案才处理验证日期输入。