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 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 false
myvar
checks 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.call
or.apply
the method fromObject.prototype
directly 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
instanceof
orDate.prototype.isPrototypeOf
.
!isNaN(myvar)
finally checks whether the value was not anInvalid Date
.
Source : Stackoverflow