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

本文标签: unexpected javascript date behaviorStack Overflow