0

When I type in '02/27/2010' it is not a NaN. also when I type in '02/31/2010' it is also not a NaN when I use the Date and getDate("mydate") function. It will change this to March 3rd?

Is there a way to determine if the date is a real date without adding days to jump to the next month or year?

Thanks, Marc

RetroCoder
  • 2,597
  • 10
  • 52
  • 81

4 Answers4

2

This is one way:

  String.prototype.isValidDate = function(){
    var arrDate = this.split("/");
    if(arrDate.length!=3)return false;
    var month = parseInt(arrDate[0],10);
    var day = parseInt(arrDate[1],10);
    var year = parseInt(arrDate[2],10);                                  
    var dateComp = new Date(year, month-1, day);
    return (month == dateComp.getMonth()+1 &&
            day == dateComp.getDate() && 
            year == dateComp.getFullYear());
  };

  alert("2/1/2011".isValidDate());  
  alert("2/31/2011".isValidDate());
  alert("02/01/2011".isValidDate());

Example

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You may checkout datejs for everything that's dates manipulations in javascript.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    @Rudie, sure, it all depends on what are the requirements. Sometimes 26KB are better than reinventing the wheel by writing some 2KB of crappy javascript code that works in 73% of the cases and breaks in the other 27% and that we need to maintain and that only the author and God are capable of. – Darin Dimitrov May 03 '11 at 22:14
  • Excellent point. It all depends on the case. I've saved the website to ma favs =) – Rudie May 03 '11 at 23:00
0

Detecting an "invalid date" Date instance in JavaScript looks like that is the answer, from what I can tell.

Community
  • 1
  • 1
Paul Zaczkowski
  • 2,848
  • 1
  • 25
  • 26
  • That will just say if it is a valid date object, it will not verify that the date supplied is the same as the user entered. – epascarello May 03 '11 at 22:33
0

//

function isvalid_mdy(s){
    var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
    A[0]-=1;
    try{
        day= new Date(A[2], A[0], A[1]);
        if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
        throw 'Bad Date ';
    }
    catch(er){
        return NaN;
    }
}
function isvalid_dmy(s){
    var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
    A[1]-=1;
    try{
        day= new Date(A[2], A[1], A[0]);
        if(day.getMonth()== A[1] && day.getDate()== A[0]) return day;
        throw 'Bad Date ';
    }
    catch(er){
        return NaN;
    }
}
kennebec
  • 102,654
  • 32
  • 106
  • 127