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!
Asked
Active
Viewed 8.2k times
4 Answers
209
Use instanceof
(myvar instanceof Date) // returns true or false

BrunoLM
- 97,872
- 84
- 296
- 452
-
10It 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/). – Christian C. Salvadó May 14 '10 at 04:55
-
6I tested it with an "Invalid Date" and it returned true!! – Roshdy Dec 07 '15 at 18:22
-
This is not working as expected in my case where I've used DHTMLX Calendar type in date field. – lnepal Dec 09 '15 at 08:25
43
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
- 35,104
- 14
- 75
- 93
-
Hmm this won't work if you have something that inherits from Date, will it? – Claudiu May 14 '10 at 03:22
-
This is how Ext JS does it. Not sure about other frameworks, but that's what I would look at. – Brian Moeskau May 14 '10 at 03:33
-
2@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. – Christian C. Salvadó May 14 '10 at 04:38
-
Well, if it inherits from Date, it is a Date object. This seems to be a really good answer! – Loupax Oct 03 '13 at 09:08
-
-2
if(obj && obj.getUTCDay){ // I'll treat it like a Date }

kennebec
- 102,654
- 32
- 106
- 127
-
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 May 14 '10 at 03:54
-
3Or 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 ;) – Brian Moeskau May 14 '10 at 04:00
-6
if (parseDate("datestring"))

Germán Rodríguez
- 4,284
- 1
- 19
- 19
-
1I assume you realize that this is not the same is checking for a Date object type, which seems to be the question? – Brian Moeskau May 14 '10 at 03:59
-