为什么 javascript getMonth 从 0 开始计数,getDate 从 1 开始计数? [英] why does javascript getMonth count from 0 and getDate count from 1?
问题描述
这个问题纯粹是为了满足我的好奇心.
This question is purely to satisfy my curiosity.
在 JavaScript Date 对象中,当您调用 getMonth()
时,它返回月份,但从 0 开始计数.
In the JavaScript Date object, when you call getMonth()
it returns the month but it counts from 0.
0 = January
1 = February
...
但是当你调用 getDate()
时,它从 1 开始计数
But when you call getDate()
it starts counting from 1
1 = 1
2 = 2
...
为什么不一致?
推荐答案
我认为这是因为在名称数组中引用会更容易,即
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()];
如果getMonth()
返回1-12
,那么程序员每次想要一个d.getMonth()-1
花式命名月份.
If getMonth()
returned 1-12
, then programmers would have to do d.getMonth()-1
everytime they wanted a fancy named month.
一个月中的几天本身没有特定的名称".getDate()
返回 1-(28-31)
.我们通常只用他们的号码来称呼他们.
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.
与 getMonth()
相同的概念也适用于 getDay()
,它根据星期几返回 0-6
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
这篇关于为什么 javascript getMonth 从 0 开始计数,getDate 从 1 开始计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!