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
getMonth in javascript gives last month
提问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() + 1
to achieve what you want.
因为getmonth()从 0 开始。你可能想要d1.getMonth() + 1
实现你想要的。
回答by letiagoalves
回答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
我怀疑这些方法由于历史原因缺乏一致性