3

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!

3 Answers 3

10

.getMonth() is zero-based. as in 0=January and 11=December

try

var month=newDate.getMonth() + 1;
Sign up to request clarification or add additional context in comments.

Comments

7

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

2 Comments

and THANK YOU! I marked the previous as the answer only because it was first - obviously yours is just as valid!
@Dutchie432: Ditto! jlisham: You're welcome - I'm glad it helped.
-1
getMonth() + 1

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getMonth

1 Comment

Welcome to Stack Overflow! Would you consider adding some narrative to explain why this code works, and what makes it an answer to the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.