The Mystery Of Javascript getDate vs getMonth Values

12 February 2016

Have you wondered why in Javascript, getMonth() returns a number from 0 to 11, whilst getDate() returns a number from 1 to 31?

It turns out this isn't a mistake or an oversight, but by design; while it doesn't explicitly say so in (page 340), getMonth returns a 0-based integer so you can use it easily with an array of month names:

var months = ["January", "February", "March", "April", "May", "June", "July",
         "August", "September", "October", "November", "December"];

var d = new Date();

var monthName = months[d.getMonth()];

But it wouldn't make sense to do so with actual date numbers as there isn't a common scenario to use those along with an array.

Either way, you still have to +1 the month value when you want to represent it numerically, or you have to -1 when you want to use it in conjuction with an array of names, but it's interesting to know why this discrepancy exists.

Tags: Javascript

Add a Comment

No Comments