Monday, August 04, 2008

Why javascript doesn't like August and September in date validation

Do you like August and September months? Well, then bad news, because JavaScript doesn't like them. Using parseInt function without base parameter to convert from text to number when validating month number 08 gives 0.
This is true only for August(month "08") and September(month "09"), so it can take a while until the error is discovered. Why is that happening? Well, probably because genious developers of Javascript API thought that people use octal (base8) as default. Numbers until 08(August, put as "08" in dates) are converted correctly because they are same in octal as in base10, and numbers after 09 are recognized correctly because they(almost never) have a non-zero leading number. In between we have our poor "08" and "09".
Fortunately, there is a parameter you can add to parseInt function which specifies the base, e.g. parseInt("09", 10). But was it really so smart to use base8 as default for numbers beginning with 0 instead of always using base10 and requiring user to explicitely enter parameter for other (less used) bases?



Alternatives for parseInt are parseFloat and Number functions:

Doesn't work correctly:
javascript:alert(parseInt("09"))

Works correctly:
javascript:alert(parseInt("09", 10))
javascript:alert(Number("09"))
javascript:alert(parseFloat("09"))



4 comments:

Anonymous said...

Cool - Very nice to know

Kripashankar said...

That's true, we had developed a application last November. On the starting of this month, customer reported to have a bug in a date functionality. I said that would be impossible, then only came to know about such an issue in javascript.

Anonymous said...

酒店打工

酒店兼職

台北酒店

打工兼差

酒店工作

酒店經紀

禮服酒店

酒店兼差

酒店上班

酒店PT

酒店

酒店喝酒

酒店消費

喝花酒

粉味

喝酒

Ecommerce developer said...

Great information.It is very helpful.Great effort.Thank u.