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:

Javascript check whether an object is a date
let isDate = function (input) { if (Object.prototype.toString.call(input) === "[object Date]") return true; return false; }; console.log(isDate("April 14, 2020 11:15:00")); console.log(isDate(new Date(96400000))); console.log(isDate(new Date(89, 5, 11, 10, 23, 20, 0))); console.log(isDate([1, 3, 5, 0]));

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

date instanceof Date

Example:

Javascript instanceof operator
let myDate = new Date(); console.log(myDate instanceof Date);
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 suggest checking if the object has a getMonth() property or not:

Javascript checking if the object has a getMonth() property
let dt = new Date("March 14, 1982 23:15:00"); if (dt.getMonth) { let month = dt.getMonth(); console.log(month); }

But if you want to check that it is a Date , and not just an object with a getMonth() function, use the following:

Javascript check that it is a Date
let dt = new Date("April 14, 2020 13:12:00"); function isValidDate(value) { let dateWrapper = new Date(value); console.log(!isNaN(dateWrapper.getDate())); } isValidDate(dt)

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.