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

前端 未结 3 1790
一整个雨季
一整个雨季 2020-11-28 11:37

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.

3条回答
  •  难免孤独
    2020-11-28 12:01

    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 
    

提交回复
热议问题