I was wondering if there is any way to check if an object is specifically a Date in JavaScript. isType returns object for Date, which isn't enough for this scenario. Any ideas? Thanks!
It will work for *most cases*, but it will fail on multi-frame DOM environments, give a look to [this article](http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/).
CMS
2010-05-14 04:55:29
+2
A:
Object.prototype.toString.call(obj) === "[object Date]"
will work in every case, and obj instanceof Date
will only work in date objects from the same view instance (window
).
Eli Grey
2010-05-14 02:00:24
Hmm this won't work if you have something that inherits from Date, will it?
Claudiu
2010-05-14 03:22:29
This is how Ext JS does it. Not sure about other frameworks, but that's what I would look at.
bmoeskau
2010-05-14 03:33:22
@Claudiu: No, but honestly, I think you'll never need to create an object instance that inherits from `Date.prototype`..., @bmoeskau, this is the safest way to detect the *kind* of an object made by the built-in constructors like `Array`, `RegExp`, `Date`, etc... other frameworks, like jQuery use this to [detect `Array` objects](http://api.jquery.com/jQuery.isArray/), [Prototype](http://www.prototypejs.org/api/object/isstring) also use it for this and to detect primitive values wrapped, since those wrappers are objects, e.g. `typeof new String("") == 'object';` and also for detecting Opera.
CMS
2010-05-14 04:38:16
If you happen to have a similar method called "getUTCDay" on a completely unrelated object this will return true for `obj` even if it isn't a Date.
John Feminella
2010-05-14 03:54:00
Or more likely, if someone *after* you writes a getUTCDay method somewhere in your code base, they'll have a nice long afternoon of debugging at some point ;)
bmoeskau
2010-05-14 04:00:50