admin管理员组文章数量:1333201
I have the following code:
var newDate=new Date('05/22/2012');
var month=newDate.getMonth();
var day=newDate.getDate()+(-2);
var year=newDate.getYear();
document.write(month+'/'+day+'/'+year);
I expected it to return '05/20/2012' but instead it returns '04/20/2012'
This makes no sense to me - can someone help me understand what's going on and how to get the correct response?
Thank you for your kind attention!
I have the following code:
var newDate=new Date('05/22/2012');
var month=newDate.getMonth();
var day=newDate.getDate()+(-2);
var year=newDate.getYear();
document.write(month+'/'+day+'/'+year);
I expected it to return '05/20/2012' but instead it returns '04/20/2012'
This makes no sense to me - can someone help me understand what's going on and how to get the correct response?
Thank you for your kind attention!
Share Improve this question asked May 22, 2012 at 16:36 jlishamjlisham 1452 silver badges12 bronze badges3 Answers
Reset to default 10.getMonth()
is zero-based. as in 0=January
and 11=December
try
var month=newDate.getMonth() + 1;
.getMonth()
is zero-based. January corresponds to 0, February to 1, etc.
As of the time of this question, the month is May, and therefore .getMonth()
returns 4
.
You want .getMonth() + 1
.
getMonth() + 1
https://developer.mozilla/en/JavaScript/Reference/Global_Objects/Date/getMonth
本文标签: unexpected javascript date behaviorStack Overflow
版权声明:本文标题:unexpected javascript date behavior - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742347615a2457843.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论