Check variable is a Date Object or not in JavaScript

We can check that a given variable is a date object or not. To check this, we have various approaches. Let check one by one.

Solution 1:

It will work for most cases, but it will fail on multi-frame DOM environments

(myvar instanceof Date) && !isNaN(myvar) // return true or false
  • Checks if object is actually a Date and not something that looks like one.
  • isNaN Ensures the Date is not an Invalid Date

Solution 2:

typeof myvar.getMonth === 'function'

Check string is date or not in JavaScript 

Solution 3:

If you need to support iframes and different contexts, you can use the accepted answer but add an extra check to identify invalid dates

(myvar && Object.prototype.toString.call(myvar) === '[object Date]' && !isNaN(myvar)) 
// returntrue or false
  1. myvar checks whether the parameter was not a falsy value (undefinednull0"", etc..)
  2. Object.prototype.toString.call(myvar) returns a native string representation of the given object type – In our case "[object Date]". Because date.toString() overrides its parent method, we need to .call or .apply the method from Object.prototype directly which ..
  3. !isNaN(myvar) finally checks whether the value was not an Invalid Date.

Source : Stackoverflow

Leave a Reply