3

I've got an object containing dates in the format YYYY-MM-DD.

I'm extracting the various year, month and day integers so I can send them to a different API.

Here's an example of my method, using substr()

Demo: http://jsfiddle.net/AppSynergy/tELsw/

OK, it works. OH NO! - it doesn't - not quite.. What's wrong with the 3rd element, where the "08" in 8th April decides to be 0 instead?

If I change "08" to another integer e.g. "03", it's fine. But "08" causes issues..

This one is driving me crazy -- what's wrong?

If you can spot it, you deserve ice-cream.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Adam Marshall
  • 693
  • 6
  • 16
  • 3
    Try having a look at this question: http://stackoverflow.com/questions/850341/workarounds-for-javascript-parseint-octal-bug – Bogdan Jun 25 '12 at 09:36
  • 1
    `08` is parsed as an octal, instead of decimal. This is why we should use the radix with parseInt()`. – David Thomas Jun 25 '12 at 09:37
  • 1
    Interesting to note that IE9 is the only browser I tested that follows the [ES5.1 spec correctly](http://ecma-international.org/ecma-262/5.1/#sec-15.1.2.2) and `parseInt("08")` results in `8` – Esailija Jun 25 '12 at 09:40

3 Answers3

7

08 is considered as an (invalid) octal literal by default.

You have to explicitly specify the radix in your call to parseInt() in order for this token to be considered as a decimal (base 10) number:

$("#debug").append(parseInt(date.substr(5, 2), 10) + " / ");
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • OMG.. octal default? I would **never** have thought of that! Adding the specific base of 10 solves it perfectly - thanks Frédéric and others that commented! - A – Adam Marshall Jun 25 '12 at 10:05
3

You need to use parseInt with radix/base of 10 since preceding 0 converts your number in octal notation.

parseInt(yourNum, 10);

Because of that reason, it turns out that you should ALWAYS specify base when using parseInt unless you are not working on base 10 numbers.

Blaster
  • 9,414
  • 1
  • 29
  • 25
2

If string begins with "0", javascript will think the radix is eight (octal).

You need to tell javascript to parse the string by base of 10.

$.each(testData, function(i, val) {
    // sort out the date format
    var date = val.trim();
    $('#debug').append(date+' ==><br />');
    $('#debug').append(parseInt(date.substr(0, 4), 10)+' / ');
    $('#debug').append(parseInt(date.substr(5, 2), 10)+' / ');
    $('#debug').append(parseInt(date.substr(8, 2), 10)+'<br /><br />');
});
xdazz
  • 158,678
  • 38
  • 247
  • 274