为什么javascript getMonth从0开始计数,getDate从1开始计数? [英] why does javascript getMonth count from 0 and getDate count from 1?

查看:691
本文介绍了为什么javascript getMonth从0开始计数,getDate从1开始计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题纯粹是为了满足我的好奇心。



在JavaScript Date对象中,当调用 getMonth()它返回月份,但从0开始。

  0 =一月
1 =二月
...

但是当您调用 getDate()它从1开始计数

  1 = 1 
2 = 2
...

为什么不一致?

解决方案

我认为这是因为在名称数组中更容易引用,例如

  var months =八月,九月,十月,十一月,十一月,十一月,十月十二月]; 

var d = new Date();

var namedMonth = months [d.getMonth()];

如果 getMonth()返回 1-12 ,那么程序员每次想要一个花哨的月份,都必须要做 d.getMonth() - 1 p>

本月几天没有具体的名字。 getDate()返回 1-(28-31)。除非你是日本人,否则我们通常只是用他们的号码来引用它们,但是 Brendan Eich 没有。



getMonth()相同的概念适用于 getDay()还可以根据星期几返回 0-6

  var days = [Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday 

var namedDay = days [d.getDay()];

所有这些返回如下:

  console.log(Month:month [+ d.getMonth()+]:+ namedMonth); 
//月:month [3]:April
console.log(Day:days [+ d.getDay()+]:+ namedDay);
//天:天[4]:星期四


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.

0 = January
1 = February 
...

But when you call getDate() it starts counting from 1

1 = 1
2 = 2
... 

Why the inconsistency?

解决方案

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()];

If getMonth() returned 1-12, then programmers would have to do d.getMonth()-1 everytime they wanted a fancy named month.

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, unless you are Japanese, but Brendan Eich is not.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆