How to Check Whether an Object is a Date
In this tutorial, we suggest several methods of checking whether the parameter passed to the method is of type Date or not.
There is a workable and probably the best solution that checks the object's class:
Object.prototype.toString.call(input) === '[object Date]'
Example:
There are also some other methods. One of them is using the instanceof operator, like this:
date instanceof Date
Example:
There is another solution that suggest checking if the object has a getMonth() property or not:
But if you want to check that it is a Date , and not just an object with a getMonth() function, use the following:
The given piece of code will create either a clone of the value if it is a Date, or create an invalid date. You can then check if the value of the new date is invalid or not.
The toString() Method
All objects have a toString() method called when an object should be represented as a text value, or an object is referred to in a manner in which a string is expected. Every object inherits the method descended from Object. If it is not overridden in a custom object, the toString() method returns "[object type]", where type is the type of the object.