Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there an isDate function in jQuery?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

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..

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...