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.
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 an
typeof myvar.getMonth === 'function'
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
myvarchecks whether the parameter was not a falsy value (
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
.applythe method from
Object.prototypedirectly which ..
!isNaN(myvar)finally checks whether the value was not an
Source : Stackoverflow