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.
Table of Contents
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
Dateand not something that looks like one. isNaNEnsures the Date is not anInvalid 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 falsemyvarchecks whether the parameter was not a falsy value (undefined,null,0,"", etc..)Object.prototype.toString.call(myvar)returns a native string representation of the given object type – In our case"[object Date]". Becausedate.toString()overrides its parent method, we need to.callor.applythe method fromObject.prototypedirectly which ..- Bypasses user-defined object type with the same constructor name (e.g.: “Date”)
- Works across different JS contexts (e.g. iframes) in contrast to
instanceoforDate.prototype.isPrototypeOf.
!isNaN(myvar)finally checks whether the value was not anInvalid Date.
Source : Stackoverflow
