javascript 中的 getMonth 给出上个月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18624326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:38:40  来源:igfitidea点击:

getMonth in javascript gives last month

javascriptdate

提问by developer747

I am using a datepicker which gives a date in the format Sun Jul 7 00:00:00 EDT 2013. Even though the month says July, if I do a getMonth, it gives me the previous month.

我正在使用日期选择器,它以 Sun Jul 7 00:00:00 EDT 2013 格式给出日期。即使月份是 7 月,如果我执行 getMonth,它也会给我上个月。

var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth());//gives 6 instead of 7

What am I doing wrong?

我究竟做错了什么?

回答by Rahul Tripathi

Because getmonth()start from 0. You may want to have d1.getMonth() + 1to achieve what you want.

因为getmonth()从 0 开始。你可能想要d1.getMonth() + 1实现你想要的。

回答by letiagoalves

getMonth()function is zero indexed based. You need to do d1.getMonth() + 1

getMonth()函数是基于零索引的。你需要做d1.getMonth() + 1

Recently I used Moment.jslibrary and never looked back. Try it!

最近我使用了Moment.js库并且再也没有回头。试试看!

回答by jasonleonhard

Presuming you use your variable

假设你使用你的变量

var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");

Month requires a +1 to be accurate, it starts counting at 0

月份需要 +1 才能准确,它从 0 开始计数

d1.getMonth() + 1 // month 

In contrast.... these methods DON'T need a plus 1

相比之下......这些方法不需要加1

d1.getSeconds()   // seconds 
d1.getMinutes()   // minutes 
d1.getDate()      // date    

And notice it is .getDate()NOT .getDay()

并注意它.getDate()不是。getDay()

d1.getDay()       // day of the week as a 

Hope this helps

希望这可以帮助

I suspect these methods lack consistency for historical reasons

我怀疑这些方法由于历史原因缺乏一致性