Nathan Hoad


Javascript parseInt problem

A while ago when I was working on an Event System I wrote a simple Javascript date formatting script. The script translated something like '11-02-2008' to something like 'Monday, 2 February 2008' using the Javascript Date object and a few parseInts.

After a while, something seemingly random started happening: any date in September or October displayed the wrong day name. I soon traced my problem back to a call to parseInt().

// fails if month is '08' or '09'
var m = parseInt(month);

For some reason it was causing the months index to become 0. After a bit of Googling I found an answer. The function parseInt tries to be clever and guess which base you are using to convert your string to an integer. Although it usually defaults to base 10, when given strings starting with '0', it assumes that you are parsing an octal number (strings starting with '0x', it assumes hexadecimal).

parseInt('07'); // 7
parseInt('08'); // 0
parseInt('09'); // 0
parseInt('10'); // 10

A workaround is to always pass the radix to parseInt:

parseInt('08', 10);
parseInt('09', 10);

For more information, check out Mozilla's Developer Center

If you liked this article then check out my free office sport app, Athletable. Or you can grab Brainial, my free iOS puzzle game.