Why there is need to add 1 to the month for this date conversion?

╄→尐↘猪︶ㄣ 提交于 2019-12-02 23:23:51

问题


I have this date variable in javascript $scope.dt and the contents is Tue Jul 08 2014 00:00:00 GMT+0800 (Malay Peninsula Standard Time). I want to convert it to return a string that is 2014-7-8 (YYYY-MM-DD).

Below is the function I wrote;

function convertDate_YYYYMMDD(d)
{
    var curr_date = d.getDate();
    var curr_month = d.getMonth()+1; //why need to add one?
    var curr_year = d.getFullYear();
    return (curr_year + "-" + curr_month + "-" + curr_date );
}

It works fine. What I don't understand is why do I need to add 1 to get the correct curr_month? If I do not do this, the month will always be off by one. The code works but I don't know why it works.

Can someone advise?


回答1:


That's legacy of C. The month in timestamps are zero-based.

Compare Date.getMonth():

The value returned by getMonth is an integer between 0 and 11. 0 corresponds to January, 1 to February, and so on.

struct tm:

int tm_mon month of year [0,11]

And why the months start with zero in many programming languages is explained in here: Zero-based month numbering. Paraphrased: Using January == 0 was useful in ancient times, and now we re stuck with it.




回答2:


http://www.w3schools.com/jsref/jsref_getmonth.asp

The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.

Note: January is 0, February is 1, and so on.




回答3:


The month range is 0-11. i.e. For January it will be 0 and for December it will return you 11. Therefore we need to add 1 to it.

Check this



来源:https://stackoverflow.com/questions/24629937/why-there-is-need-to-add-1-to-the-month-for-this-date-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!