检测“无效日期” 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'
写入的任何想法都是ValidDate
函数?
- 灰推荐
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.
推荐答案
而不是使用new Date(),您应该使用:
Instead of using "new Date()" you should use:
var timestamp=Date.parse('foo')
if (isNaN(timestamp)==false)
{
var d=new Date(timestamp);
}
Date.parse() / code>返回一个时间戳,一个整数,表示自1970 / Jan / 1970以来的毫秒数。如果无法解析提供的日期字符串,它将返回
NaN
。
这篇关于检测“无效日期” JavaScript中的日期实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文