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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742347615a4426865.html
评论列表(0条)