为什么此日期转换需要在月份中加1? [英] Why there is need to add 1 to the month for this date conversion?
问题描述
我在javascript $ scope.dt
中有此日期变量,内容为 2014年7月8日星期二00:00:00 GMT + 0800(马来半岛标准时间)
。我想将其转换为返回 2014-7-8
(YYYY-MM-DD)的字符串。
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).
下面是我写的函数;
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 );
}
工作正常。我不明白为什么我需要加1才能获得正确的 curr_month
?如果我不这样做,这个月将永远是一个月。该代码有效,但我不知道为什么。
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.
有人可以建议吗?
推荐答案
这是C的遗产。时间戳中的月份是从零开始的。
That's legacy of C. The month in timestamps are zero-based.
比较 Date.getMonth():
getMonth返回的值是0到11之间的整数。0对应于1月,1到2月,依此类推。
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一年的月份[0,11]
为什么在许多编程语言中月份以零开头是为什么:基于零的月份编号。释义:在古代,使用一月== 0很有用,现在我们坚持使用它。
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.
这篇关于为什么此日期转换需要在月份中加1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!