Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether a given string represents a date?

Tags:

Is there an isDate function in jQuery?

It should return true if the input is a date, and false otherwise.

like image 758
Kuttan Sujith Avatar asked Oct 07 '10 10:10

Kuttan Sujith


2 Answers

If you don't want to deal with external libraries, a simple javascript-only solution is:

function isDate(val) {     var d = new Date(val);     return !isNaN(d.valueOf()); } 

UPDATE:     !!Major Caveat!!
@BarryPicker raises a good point in the comments. JavaScript silently converts February 29 to March 1 for all non-leap years. This behavior appears to be limited strictly to days through 31 (e.g., March 32 is not converted to April 1, but June 31 is converted to July 1). Depending on your situation, this may be a limitation you can accept, but you should be aware of it:

>>> new Date('2/29/2014') Sat Mar 01 2014 00:00:00 GMT-0500 (Eastern Standard Time) >>> new Date('3/32/2014') Invalid Date >>> new Date('2/29/2015') Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time) >>> isDate('2/29/2014') true  // <-- no it's not true! 2/29/2014 is not a valid date! >>> isDate('6/31/2015') true  // <-- not true again! Apparently, the crux of the problem is that it       //     allows the day count to reach "31" regardless of the month.. 
like image 132
mwolfe02 Avatar answered Sep 25 '22 13:09

mwolfe02


simplest way in javascript is:

function isDate(dateVal) {   var d = new Date(dateVal);   return d.toString() === 'Invalid Date'? false: true; } 
like image 33
isambitd Avatar answered Sep 25 '22 13:09

isambitd