如何检查对象是否是日期? [英] How to check whether an object is a date?
问题描述
我在网页上有一个烦人的错误:date.GetMonth()不是一个功能。所以我想我做错了,因为某个地方,对象日期不是Date类型的对象。 我如何检查Javascript中的数据类型?我尝试添加一个 if(date)但不起作用。
I have an annoying bug in on a webpage: "date.GetMonth() is not a function". So I suppose that I am doing something wrong since somewhere and the object 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的参数的类型为Date。
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
operator,ie但是它也将返回真实的无效日期,例如 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屋!