I've noticed that in JavaScript, when creating a Date, months are zero based, and days aren't.

For example:

var foo = new Date(2012, 1, 1)

produces February 1st 2012

Why is this?

  • 6
    months = ['Jan', 'Feb',..., 'Nov', 'Dec']; month = months[date.getMonth()]; – zzzzBov Dec 13 '12 at 18:15

Most likely the idea is, that the months are thought of as an index into an array of month names, while days are simply "counted".

  • 22
    Where this makes sense from an answer stand point, it's bat crap crazy to think this logic has been around for how long now and i've never questioned it before. – rlemon Dec 13 '12 at 15:12
  • 2
    @rlemon The fact that you've never questioned that logic before only proves that it makes sense :) – Sergey Kalinichenko Dec 13 '12 at 15:18
  • 14
    FWIW, I never thought it made much sense. Processing dates in JavaScript was always something that made me shudder, because I'd usually forget things like this until I started debugging strange results. – FrustratedWithFormsDesigner Dec 13 '12 at 15:20
  • 2
    FWIW, I am not a front end developer and don't often have to deal with dates in Javascript aside from the occasional new Date().getTime() – rlemon Dec 13 '12 at 15:28
  • 20
    When it comes to Javascript, "this is why they did it" and "this makes a good sense" are two things you rarely hear together. – Tridus Dec 13 '12 at 17:34

It may also be that Javascript dates were meant to mimic java dates. Java has similarly used a zero based month since the beginning.

JDK API v1.0.2 : Date.getMonth()

  • 6
    And the java spec mirrors the C tm structure. See also stackoverflow.com/questions/344380/… – user40980 Dec 13 '12 at 15:52
  • 35
    That's not to say that the Java Date API is a terribly good example of good design ;-) – Joachim Sauer Dec 13 '12 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.