92

Possible Duplicate:
Detecting an “invalid date” Date instance in JavaScript

Is there is a function IsDate() in javascript?

0

1 Answer 1

215

Try this:

var date = new Date(); console.log(date instanceof Date && !isNaN(date.valueOf())); 

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

Sign up to request clarification or add additional context in comments.

10 Comments

new Date('derp') instanceof Date // true
@JulianH.Lam I've added a isNaN validation to the valueOf property to handle this case. Thanks!!!
Returns true for new Date('06/31/2016') since Javascript converts that to 7/1/2016. Returns false for 06/32/2016 however. Just something to keep in mind. Only drawback.
@JulianH.Lam - but then 'Do NOT Convert Me as a date 1' also returns true
I've actually expanded my example. Even using MomentJS's isValid() function is incorrect. It seems like JavaScript uses the Date.parse function - when it fails to evaluate the text, it just uses the numbers, so new Date('Test 1') evaluates to the same as new Date('1'). The only way to get it working correctly would be either to develop your own string parsing, or you could use date-fns.org - the isValid() function seems to work correctly.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.