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?
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.
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.
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.
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.
来源:https://stackoverflow.com/questions/24629937/why-there-is-need-to-add-1-to-the-month-for-this-date-conversion