120

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!

0

4 Answers 4

223

Use instanceof

(myvar instanceof Date) // returns true or false 
Sign up to request clarification or add additional context in comments.

3 Comments

It will work for most cases, but it will fail on multi-frame DOM environments, give a look to this article.
I tested it with an "Invalid Date" and it returned true!!
This is not working as expected in my case where I've used DHTMLX Calendar type in date field.
45

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

Hmm this won't work if you have something that inherits from Date, will it?
This is how Ext JS does it. Not sure about other frameworks, but that's what I would look at.
@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.
Well, if it inherits from Date, it is a Date object. This seems to be a really good answer!
Wouldn't testing against d.constructor.name better?
-4

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

2 Comments

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.
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 ;)
-8
if (parseDate("datestring")) 

2 Comments

I assume you realize that this is not the same is checking for a Date object type, which seems to be the question?
oooh!! i misunderstood the question =/ my bad

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.