This morning I noticed a peculiar issue with the JavaScript setFullYear method.
When using the method like so:
d.setFullYear(2012,2,8);
The correct value is returned:
Thu Mar 08 2012 10:30:04 GMT+0000 (GMT Standard Time)
However if I use the parseInt method to return the integers, the date returned is incorrect:
d.setFullYear(parseInt("2012"), parseInt("02"), parseInt("08"));
returns:
Wed Feb 29 2012 10:31:30 GMT+0000 (GMT Standard Time)
It appears that the parseInt method is returning the incorrect values, but when I test it:
document.write(parseInt("2"));
Then the correct value is returned (2)
A working fiddle is here: http://jsfiddle.net/rXByJ/
Does the problem lie with parseInt or with setFullYear?
The problem is that parseInt('08')
is 0
. This works:
d.setFullYear(parseInt("2012"), parseInt("02"), 8);
Both parseInt('08') and parseInt('09') return zero because the function tries to determine the correct base for the numerical system used. In Javascript numbers starting with zero are considered octal and there's no 08 or 09 in octal, hence the problem.
http://www.ventanazul.com/webzine/articles/issues-parseint-javascript
Solution is to use the second parameter:
parseInt('08', 10)
Or
Number('08')
Also see How do I work around JavaScript's parseInt octal behavior?
This post here on stackoverflow has a very detailed explanation on why one should use parseInt with a base
or radix
yes thats true parseInt('08') will return 0 instead of 8 because it takes 08 as octal number and converts into 0 so you should use parseInt('08', 10) where second parameter specifies base for conversion, that is 10 for decimal
so in short always specify base when using parseInt :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With