W3docs

How to Check Whether an Object is a Date

Read this JavaScript tutorial and learn several ways that are used for checking whether the parameter passed to the method is of type Date object or not.

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:

javascript— editable

There are also some other methods. One of them is using the instanceof operator, like this:

date instanceof Date

Example:

javascript— editable
Warning

However, it will return true for invalid dates too, for example, new Date('random_string') is also an instance of Date. This will fail if objects are passed across frame boundaries.

There is another solution that suggests checking if the object has a getMonth() property or not:

javascript— editable

But if you want to validate whether a value represents a valid date, use the following:

javascript— editable

This code attempts to convert the value to a Date object. If the conversion results in a valid date, it returns true; otherwise, it returns false.

The toString() Method

All objects have a <kbd class="highlighted">toString()</kbd> 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 from Object. If it is not overridden in a custom object, the <kbd class="highlighted">toString()</kbd> method returns "[object type]", where type is the type of the object. This behavior is exactly what the first method leverages for type checking.

Here is a practical example:

console.log(Object.prototype.toString.call(new Date())); // "[object Date]"
console.log(Object.prototype.toString.call("April 14, 2020")); // "[object String]"
console.log(Object.prototype.toString.call({})); // "[object Object]"