85

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

Is there is a function IsDate() in javascript?

Community
  • 1
  • 1
Guilherme Costa
  • 1,249
  • 2
  • 12
  • 13

1 Answers1

205

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

Brien Foss
  • 3,336
  • 3
  • 21
  • 31
Gabriel Jürgens
  • 3,055
  • 3
  • 20
  • 19
  • 32
    `new Date('derp') instanceof Date // true` – Julian H. Lam Oct 21 '13 at 22:00
  • 3
    @JulianH.Lam I've added a isNaN validation to the valueOf property to handle this case. Thanks!!! – Gabriel Jürgens Oct 21 '13 at 23:10
  • 2
    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. – Brian Edwards Jul 22 '16 at 18:23
  • 3
    @JulianH.Lam - but then 'Do NOT Convert Me as a date 1' also returns true – schmoopy Feb 08 '17 at 20:14
  • i think is not trust, several tests with wrong date return true – Felipe Maricato Moura Nov 28 '19 at 19:54
  • Instead of date instanceof Date you can also use Object.prototype.toString.call(date) === '[object Date]' . The original source was found here https://stackoverflow.com/questions/643782/how-to-check-whether-an-object-is-a-date .Thank you to both the accepted answer authors. – KenBuckley Aug 25 '20 at 16:44
  • 1
    @FelipeMaricatoMoura If you found a counterexample date that fails for you, it's helpful to share what that date might be, exactly. – ggorlen May 15 '21 at 00:27
  • I've been searching for a way to consistently check whether a string is a valid date. Up to now everything has failed, including this. Using a random string ending with a number will evaluate as a correct date, so checking the validity or class will come back as TRUE. For reference: https://jsfiddle.net/juro/8ogz3sda/ . – roland Sep 16 '21 at 08:15
  • 3
    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 https://date-fns.org/ - the `isValid()` function seems to work correctly. – roland Sep 16 '21 at 13:03