Javascript 30 Nov 2010 plus 3 months equal to 2 Mar 2011
with this script
var d = new Date(2010, 10, 30);
var e = new Date(d.getFullYear(), d.getMonth() + 3, d.getDate());
document.write(d + "<br>" + e);
why 30 Nov 2010 plus 3 months equal to 2 Mar 开发者_高级运维2011? not 28 Feb 2011?
30 Nov 2010 and 23 Feb 2011 are the last day of the month.
http://jsfiddle.net/jWh2M/
In your example, the date you specify is
30 Feb 2011
that gets converted into
2 Mar 2011
which kind of makes sense, doesn't it?
You should definitely choose a different method of adding the time span.
Either calculate the last day of each month explicitly, or alternatively, use a date library like date.js. I haven't used that one myself, but SO user @CMS recommends it, that's good enough for me.
Looking at the syntax, this might work in date.js:
Date.parse('November 30th 2010 + 3 months');
You can get the last day of a month by using this function here:
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
And set the new day to it, if your month 'overflows'.
精彩评论