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!
4 Answers
Use instanceof
(myvar instanceof Date) // returns true or false 3 Comments
Christian C. Salvadó
It will work for most cases, but it will fail on multi-frame DOM environments, give a look to this article.
Roshdy
I tested it with an "Invalid Date" and it returned true!!
lnepal
This is not working as expected in my case where I've used DHTMLX Calendar type in date field.
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).
5 Comments
Claudiu
Hmm this won't work if you have something that inherits from Date, will it?
Brian Moeskau
This is how Ext JS does it. Not sure about other frameworks, but that's what I would look at.
Christian C. Salvadó
@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, Prototype 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.Loupax
Well, if it inherits from Date, it is a Date object. This seems to be a really good answer!
Derek 朕會功夫
Wouldn't testing against
d.constructor.name better?if(obj && obj.getUTCDay){ // I'll treat it like a Date }
2 Comments
John Feminella
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.Brian Moeskau
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 ;)
if (parseDate("datestring")) 2 Comments
Brian Moeskau
I assume you realize that this is not the same is checking for a Date object type, which seems to be the question?
Germán Rodríguez
oooh!! i misunderstood the question =/ my bad