views:

78

answers:

4

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!

+2  A: 

Use instanceof

(myvar instanceof Date) // returns true or false
BrunoLM
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
+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
Hmm this won't work if you have something that inherits from Date, will it?
Claudiu
This is how Ext JS does it. Not sure about other frameworks, but that's what I would look at.
bmoeskau
@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
A: 

if(obj && obj.getUTCDay){ // I'll treat it like a Date }

kennebec
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
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
A: 
if (parseDate("datestring"))
GerManson
I assume you realize that this is not the same is checking for a Date object type, which seems to be the question?
bmoeskau
oooh!! i misunderstood the question =/ my bad
GerManson