我想知道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());
});
对于日期FNS,有一个名为isExists的函数。它检查日期是否存在(2月31日不应存在)。
示例:
// For the valid date:
const result = isExists(2018, 0, 31)
//=> true
// For the invalid date:
const result = isExists(2018, 1, 31)
//=> false
文档:https://date-fns.org/v2.28.0/docs/isExists
日期对象到字符串是检测两个字段是否为有效日期的更简单可靠的方法。例如,如果在日期输入字段中输入此“-------”。上面的一些答案行不通。
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
var startDate = new Date($(params).val());
var endDate = new Date(value);
if(startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {
return false;
} else {
return endDate > startDate;
}
},'Must be greater than {0}.');