DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jason has posted 22 posts at DZone. View Full User Profile

JavaScript IsDate Function

  • submit to reddit
        JavaScript function that determines if a variable is a proper Date object including a valid date.

function isDate (x) 
  return (null != x) && !isNaN(x) && ("undefined" !== typeof x.getDate); 


Charles Beebe replied on Tue, 2012/05/15 - 10:36am

@Snippets Manager: thanks for the help -- this was better than the answers I found on SO!

Jason McDonald replied on Wed, 2007/05/16 - 7:11pm

Explicitness. "return x && ..." will eval to false if x is undefined and I think if x.getTime() == epoch (aka 0 time). Generally, I prefer my JavaScript to not treat undefined the same as null due to design problems it creates in larger code bases. Actually, this code may not handle Infinity and -Infinity as valid Dates, I need to check on that. I may have just thought of a better way to handle the class check as well.

Snippets Manager replied on Sun, 2009/03/01 - 8:43pm

Why ( null != x ) and not just function isDate (x) { return x && !isNaN(x) && ("undefined" !== typeof x.getDate); }