Neets
Neets

Reputation: 4232

wrong date created with Javascript

I have a problem that seems so senseless that I'm sure I'm missing something really stupid. I have the following Javascript function that validates a date:

function validateDate(date){
    var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    if(!re.test(date))
        return false;

    var separator = (date.indexOf("/") != -1) ? "/" : "-";
    var aux = date.split(separator);
    var day = parseInt(aux[0]);
    var month = parseInt(aux[1]);
    var year = parseInt(aux[2]);
    alert(aux[0]+" "+aux[1]+" "+aux[2]);
    var dateTest = new Date(year,month-1,day);
    alert(dateTest); //2nd alert
    if(dateTest.getDate() != day)
        return false;
    if(dateTest.getMonth()+1!= month)
        return false;
    if(dateTest.getFullYear() != year)
        return false;

    return true;    
}

the first alert always shows the correct values. if the incoming date is for example 05/07/2011, everything works fine. The second alert shows "Tue Jul 5 00:00:00 UTC+0200 2011" which is right. but now, if i change the date month to august or september, the created date is wrong. for example, with date 05/08/2011, the second alert will show "Sun Dec 5 00:00:00 UTC+0100 2010".

anyone knows what could be happening??

Upvotes: 3

Views: 150

Answers (1)

Dennis
Dennis

Reputation: 32608

Make sure you supply a radix to parseInt. If you don't, it will "guess" based on the string. In this case, your 08 is being parsed as an octal value because of the prefixed zero and you get 0 back.

var day = parseInt(aux[0], 10);
var month = parseInt(aux[1], 10);
var year = parseInt(aux[2], 10);

Supplying a base ten number will get you the correct result.

//Parsing numbers:
parseInt("06");  // 6, valid octal
parseInt("07");  // 7, valid octal
parseInt("08");  // 0, invalid octal
parseInt("09");  // 0, invalid octal
parseInt("10");  // 10, parsed as decimal
parseInt("11");  // 11, parsed as decimal
parseInt("12");  // 12, parsed as decimal

Upvotes: 5

Related Questions