How to check whether an object is a 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?

Thanks!

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.


As an alternative to duck typing via

typeof date.getMonth === 'function'

you can use the instanceof operator, ie But it will return true for invalid dates too, eg new Date('random_string') is also instance of Date

date instanceof Date

This will fail if objects are passed across frame boundaries.

A work-around for this is to check the object's class via

Object.prototype.toString.call(date) === '[object Date]'

您可以使用以下代码:

(myvar instanceof Date) // returns true or false

The function is getMonth() , not GetMonth() .

Anyway, you can check if the object has a getMonth property by doing this. It doesn't necessarily mean the object is a Date, just any object which has a getMonth property.

if (date.getMonth) {
    var month = date.getMonth();
}
链接地址: http://www.djcxy.com/p/52190.html

上一篇: 传递JavaScript函数作为参数

下一篇: 如何检查一个对象是否是日期?