unexpected javascript date behavior - Stack Overflow

I have the following code:var newDate=new Date('05222012');var month=newDate.getMonth();v

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 badges
Add a ment  | 

3 Answers 3

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742347615a4426865.html

相关推荐

  • unexpected javascript date behavior - Stack Overflow

    I have the following code:var newDate=new Date('05222012');var month=newDate.getMonth();v

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信