Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date method inconsistency - getDate vs getMonth

This caused me a bit of a headache last night and I wanted to understand why the getDate method in the Date object is 1 based (returns values from 1-31) while the getMonth method is 0 based (returns 0-11). I'm wondering why there is this inconsistency in methods for the same object.

I understand why it's difficult to change the behavior now but are there any reasons this was designed like this in the first place?

Documentation can be found here: http://www.w3schools.com/jsref/jsref_obj_date.asp

like image 265
Dan Goldin Avatar asked Mar 13 '12 15:03

Dan Goldin


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.

How to get the time from new Date in JavaScript?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.


1 Answers

So I dropped Brendan Eich a tweet asking him the question (for those who don't know he is the creator of JS) and his response was:

@magrangs because that is how java.util.Date did it.

https://twitter.com/BrendanEich/status/179610205317902337

like image 50
mbx-mbx Avatar answered Oct 21 '22 12:10

mbx-mbx