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]'

Leave a Comment