Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does javascript getMonth count from 0 and getDate count from 1?

This question is purely to satisfy my curiosity.

In the JavaScript Date object, when you call getMonth() it returns the month but it counts from 0.

0 = January 1 = February  ... 

But when you call getDate() it starts counting from 1

1 = 1 2 = 2 ...  

Why the inconsistency?

like image 525
PrimeLens Avatar asked Apr 03 '13 22:04

PrimeLens


People also ask

Why is getMonth 0 based?

This is because the getMonth method returns a zero-based number between 0 and 11 . For example, January is 0 , February is 1 , March is 2 , etc. If you need to get a one-based value for the month, simply add 1 to the result. Copied!

Is getDate zero-based?

Zero-based counting Specifically, getMonth() counts from 0, whereas getDate() counts from 1.

What does the getMonth () method of the date object return?

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).


2 Answers

I assume it's because it would be easier to reference in an array of names, i.e.

var months = ["January", "February", "March", "April", "May", "June", "July",          "August", "September", "October", "November", "December"];  var d = new Date();  var namedMonth = months[d.getMonth()]; 

If getMonth() returned 1-12, then programmers would have to do d.getMonth()-1 everytime they wanted a fancy named month.

Days of the month don't have specific "names" per se. The getDate() returns 1-(28-31). We usually just refer to them by their number.

The same concept as getMonth() applies for getDay() also, which returns 0-6 based on the day of the week

var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];  var namedDay = days[d.getDay()]; 

All this returns something like:

console.log("Month: month[" + d.getMonth() + "]: " + namedMonth);  //Month: month[3]:  April console.log("Day: days[" + d.getDay() + "]: " + namedDay);  // Day: days[4] : Thursday  
like image 74
SomeShinyObject Avatar answered Oct 13 '22 09:10

SomeShinyObject


Coming a bit late to this, but the correct answer is here:

https://stackoverflow.com/a/41992352/134120

They (the creators of JavaScript) copied the functionality from the corresponding class in Java (which in turn seems to have been copied from C). And so we're propagating the mistakes of the past 🤦‍♂️

like image 24
AsGoodAsItGets Avatar answered Oct 13 '22 10:10

AsGoodAsItGets