Invalid date generated with Javascript

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

function validateDate(date){
    var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
        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 warning always shows the correct values. if the incoming date, for example 05/07/2011

, everything works fine. The second warning displays "Tue Jul 5 00:00:00 UTC+0200 2011"

what is true. but now if I change the date of the month to August or September the date created is wrong. for example with a date 05/08/2011

, a second warning will show "Sun Dec 5 00:00:00 UTC+0100 2010"


does anyone know what might be going on?


source to share

1 answer

Make sure you set the radius parseInt

. If you don't, it will "guess" based on the string. In this case, yours is 08

parsed as an octal value because of the zero prefix and you get 0


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


Supplying a base ten digit number will give 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




All Articles