How to check whether an object is a date?
As an alternative to duck typing via
typeof date.getMonth === 'function'
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.
A work-around for this is to check the object's class via
Object.prototype.toString.call(date) === '[object Date]'
You can use the following code:
(myvar instanceof Date) // returns true or false
In order to check if the value is a valid type of the standard JS-date object, you can make use of this predicate:
function isValidDate(date) {
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
-
date
checks whether the parameter was not a falsy value (undefined
,null
,0
,""
, etc..) -
Object.prototype.toString.call(date)
returns a native string representation of the given object type - In our case"[object Date]"
. Becausedate.toString()
overrides its parent method, we need to.call
or.apply
the method fromObject.prototype
directly which ..- Bypasses user-defined object type with the same constructor name (e.g.: "Date")
- Works across different JS contexts (e.g. iframes) in contrast to
instanceof
orDate.prototype.isPrototypeOf
.
-
!isNaN(date)
finally checks whether the value was not anInvalid Date
.
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();
}