检测“无效日期"JavaScript 中的日期实例 [英] Detecting an "invalid date" Date instance in JavaScript
本文介绍了检测“无效日期"JavaScript 中的日期实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想区分 JS 中的有效日期对象和无效日期对象,但不知道如何区分:
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:
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
函数有什么想法吗?
Any ideas for writing an isValidDate
function?
- Ash 推荐使用
Date.parse
来解析日期字符串,它提供了一种权威的方式来检查日期字符串是否有效. - 如果可能的话,我希望我的 API 接受一个 Date 实例,并且能够检查/断言它是否有效.Borgar 的解决方案可以做到这一点,但我需要跨浏览器对其进行测试.我也想知道有没有更优雅的方式.
- Ash 让我考虑完全不让我的 API 接受
Date
实例,这将最容易验证. - Borgar 建议测试
Date
实例,然后测试Date
的时间值.如果日期无效,则时间值为NaN
.我检查了 ECMA-262 并且这种行为符合标准,这正是我正在寻找的.li>
- Ash recommended
Date.parse
for parsing date strings, which gives an authoritative way to check if the date string is valid. - What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.
- Ash made me consider not having my API accept
Date
instances at all, this would be easiest to validate. - Borgar suggested testing for a
Date
instance, and then testing for theDate
's time value. If the date is invalid, the time value isNaN
. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.
推荐答案
我会这样做:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d.getTime())) { // d.valueOf() could also work
// date is not valid
} else {
// date is valid
}
} else {
// not a date
}
更新 [2018-05-31]:如果您不关心来自其他 JS 上下文(外部窗口、框架或 iframe)的 Date 对象,可能更喜欢这种更简单的形式:>
Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
这篇关于检测“无效日期"JavaScript 中的日期实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文