Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is January 0 in Javascript date object while year, day, hour, ... starts to 1? [duplicate]

Possible Duplicate:
Zero-based month numbering

Why is January month 0 in JS date object ? For instance, I would expect this snippet to create a date oject for the 8th of Februray 2013. Instead, it's March. All other fields areintuitive. Years are natural as well as day of month and time.

test_date = New Date(2013, 2, 8);

Is there any rational behind this ?

like image 455
yadutaf Avatar asked Jan 09 '13 19:01

yadutaf


People also ask

Does JavaScript month start from 0?

getMonth() – You will use this method to get the month as a number between 0-11, with each number representing the months from January to December. For example, 2 will be the index for March since it's zero-based indexing (meaning it starts from 0 ).

What is the correct creation of date () object in JavaScript?

Date objects are created with the new Date() constructor.

What does new Date () return in JavaScript?

Return value Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does.


1 Answers

Because then you can have:

var monthnames = ["Jan","Feb","Mar"....];

And access the array by:

monthnames[myDate.getMonths()]

Similarly for weekdays, where Sunday is 0.

However, years, and days are just numeric values, not indices to some greater meaning.

Side-note: Hours, minutes and seconds are zero-based in "human time" too.

like image 167
Niet the Dark Absol Avatar answered Sep 25 '22 20:09

Niet the Dark Absol