有没有办法检查变量是否是 JavaScript 中的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2831345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to check if a variable is a Date in JavaScript?
提问by Kyle Hotchkiss
I was wondering if there is any way to check if an object is specifically a Date in JavaScript. isType returns object for Date, which isn't enough for this scenario. Any ideas? Thanks!
我想知道是否有任何方法可以检查对象是否专门是 JavaScript 中的日期。isType 返回 Date 的对象,这对于这种情况是不够的。有任何想法吗?谢谢!
回答by BrunoLM
Use instanceof
使用 instanceof
(myvar instanceof Date) // returns true or false
回答by Eli Grey
Object.prototype.toString.call(obj) === "[object Date]"will work in every case, and obj instanceof Datewill only work in date objects from the same view instance (window).
Object.prototype.toString.call(obj) === "[object Date]"将适用于所有情况,并且obj instanceof Date仅适用于来自同一视图实例 ( window) 的日期对象。
回答by kennebec
if(obj && obj.getUTCDay){ // I'll treat it like a Date }
if(obj && obj.getUTCDay){ // 我会把它当作一个日期 }
回答by Germán Rodríguez
if (parseDate("datestring"))

