如何检查对象是否为日期? [英] How to check whether an object is a date?
问题描述
我在网页上有一个烦人的错误:
I have an annoying bug in on a webpage:
date.GetMonth() 不是函数
date.GetMonth() is not a function
所以,我想我做错了什么.变量 date
不是 Date
类型的对象.如何检查 Javascript 中的数据类型?我尝试添加 if (date)
,但它不起作用.
So, I suppose that I am doing something wrong. The variable date
is not an object of type Date
. How can I check for a datatype in Javascript? I tried to add a if (date)
, but it doesn't work.
function getFormatedDate(date) {
if (date) {
var month = date.GetMonth();
}
}
那么,如果我想编写防御性代码并防止格式化日期(不是一个),我该怎么做?
So, if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that?
谢谢!
更新:我不想检查日期的格式,但我想确保传递给方法 getFormatedDate()
的参数是输入日期
.
UPDATE: I don't want to check the format of the date, but I want to be sure that the parameter passed to the method getFormatedDate()
is of type Date
.
推荐答案
替代鸭子输入
typeof date.getMonth === 'function'
您可以使用 instanceof
运算符,即但对于无效日期它也会返回 true,例如new Date('random_string')
也是 Date 的实例
you can use the instanceof
operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string')
is also instance of Date
date instanceof Date
如果对象跨帧边界传递,这将失败.
This will fail if objects are passed across frame boundaries.
对此的解决方法是通过
Object.prototype.toString.call(date) === '[object Date]'
这篇关于如何检查对象是否为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!