JavaScript Date Object and Code Convention

By | February 27, 2009

“is Code Convention important?”, I couldn’t find better time to answer this with a big, decorated, shiny, flashing “YES” more than now!

I was doing some coding with JavaScript in which I needed to create a Date object and add to it 30 days, simple job! So I did the following:

    var x = new Date();

    x.setFullYear(2009, 3, 12);//Create date 12th of March, 2009

    x.setDate(x.getDate() + 30);


Great, when I checked the result it was: “Tue May 12 … 2009“! OMG why May?!, where did the additional month come from?! if I am in 12th of March and I add 30 days I expect it to be 11th of April, what is going on?!

God knows how much time I spent checking that cheesy 3rd line in my code, what could be wrong in it? maybe the “getDate()” doesn’t really return the proper type needed to set a new date? I tried all various ways doing it, checking many “solutions” scattered all over the web.

[Give your self sometime to figure it out before continue reading].

Well, the problem actually wasn’t in the 3rd line at all, it was in the 2nd! see that 2nd parameter with the value “3”? it is 0-based numeric! why on earth would it be 0-based?! any sane developer who never knew this fact would instantly deal with it “3 as March”.

Code Convention is as important as documentation; if I need documentation to know how to deal with piece of code and save me time to figure it out, Code Convention is as important.

Leave a Reply

Your email address will not be published. Required fields are marked *