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??
Make sure you supply a radix to
parseInt. If you don’t, it will “guess” based on the string. In this case, your08is being parsed as an octal value because of the prefixed zero and you get0back.Supplying a base ten number will get you the correct result.