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

前端 未结 3 1799
一整个雨季
一整个雨季 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:23

    If you want to say it's inconsistency - you need to ask the creator of specification of language. According to this page JavaScript is based on ECMAScript (EDIT: see @MichaelGeary comment).

    And when you read from page 165 here, you will see that all is working exactly as it's designed.

    For you it can be inconsistency. For me it's rather a feature - 0-based values let you access Array straight away without doing calculations (see @Christopher's answer). In case of day of month you can't really access any Array. It will be weird to have Array of names of days of the month... like this:

    var namesOfDays = [
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", // and again at least 4 times ...
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday", "Monday", "Tuesday"
    ]
    

提交回复
热议问题