0

i have a weird problem in my javascript, take a look at my code below:

dateParts = document.getElementById('date').value.split('/');
newDays = 14;
year = dateParts[2];
month = parseInt(dateParts[1]) - 1;
day = parseInt(dateParts[0]) + parseInt(newDays);
alert(dateParts[0]+" + "+newDays+" = "+day);

and assume document.getElementById('date') = 07/01/2013

the calculation will give a correct result = 07 + 14 = 21

the calculation work fine at all date, except for 08/01/2013 / 09/01/2013

which the result is 08 + 14 = 14, any idea whats wrong here?

ggDeGreat
  • 1,098
  • 1
  • 17
  • 33

3 Answers3

3

Your numbers are treated as octals, since you haven't used radix within parseInt()s. You need to adjust your parseInt()s like this:

month = parseInt(dateParts[1], 10) - 1;
day = parseInt(dateParts[0], 10) + parseInt(newDays, 10);
Teemu
  • 22,918
  • 7
  • 53
  • 106
2

The leading 0 in 08 and 09 is causing JavaScript to assume the number is octal. Since those are not valid octal values, it treats them as 0. See this question for more details.

You should always use a radix when calling parseInt to avoid this problem.

Community
  • 1
  • 1
DocMax
  • 12,094
  • 7
  • 44
  • 44
1

the function is The parseInt(str, redix), if the value in the parseInt start with 0, it is assumed the radix is 8 so '09', '08' is invalid and the function returns 0. You need to call the function like parseInt('08', 10) to get the correct value.

Kai
  • 113
  • 8