TAGS :Viewed: 9 - Published at: a few seconds ago

[ function "New Date()" doing something strange ]

I have noticed that the jQuery function New Date() does something odd. I have already found a way to work around it so I don't need help. I just want to understand why it is doing this.

I have a function doing the following:

new Date(parseInt(y),parseInt(m)-1,parseInt(d))

the actual numbers are: y= '2011', m= '07', d='01'. This works fine, it returns the date 1/7/2011. But when I use m= '08' it returns "Wed Dec 01 2010"

I tracked it down to the parseInt function. Somehow parseInt('07') = 7 but parseInt('08') = 0 Does anyone know why this happens?

Answer 1


Try new Date(parseInt(y,10),parseInt(m,10)-1,parseInt(d,10))

parseInt uses base 8 if the string starts with a zero.

Answer 2


First New Date() is not a jQuery function, but plain JavaScript.

Unfortunately, JavaScript borrowed a lot from the language C, in which you write octal numbers by prepending a zero in front of it. Octal numbers a numbers which go from 0 to 7.

What you have to do, and is best practice, is to say you have decimal numbers, not octal.

Always give the radix: parseInt(y, 10), so you code will be:

new Date(parseInt(y, 10),parseInt(m, 10)-1,parseInt(d, 10))

More info about parseInt:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt