JavaScript 如何检查日期是否有效
给定一个日期对象,任务是使用JavaScript检查给定的日期是否有效。下面讨论了解决这个问题的两种方法:
方法1
- 将日期对象存储在一个变量中。
- 如果日期有效, getTime() 将始终等于它自己。
- 如果日期无效,则 getTime() 将返回NaN,而NaN不等于它自己。
- 使用 isValid() 函数来检查getTime()方法是否等于自身。
示例: 以下示例实现了上述方法。
const date = new Date("2012/2/30");
Date.prototype.isValid = function () {
// If the date object is invalid it
// will return 'NaN' on getTime()
// and NaN is never equal to itself
return this.getTime() === this.getTime();
};
function isValidateDate() {
console.log(date.isValid());
}
isValidateDate();
输出
true
方法2
- 将日期对象存储到变量 date 中。
- 使用 Object.prototype.toString.call(d) 方法检查变量 date 是否由日期对象创建。
- 如果日期有效,则 getTime() 方法将始终等于自身。
- 如果日期无效,则 getTime() 方法将返回NaN,而NaN不等于自身。
- 在此示例中, isValid()方法 检查 getTime() 是否等于自身。
示例: 此示例实现了上述方法。
const date = new Date("This is not date.");
function isValidDate() {
if (Object.prototype.toString.call(date) ===
"[object Date]") {
if (isNaN(date.getTime())) {
console.log("Invalid Date");
}
else {
console.log("Valid Date");
}
}
}
isValidDate();
输出
Invalid Date
极客教程