这里是一个函数,需要一个字符串像01-06-2011
,把它变成一个日期变量,增加了四个月,返回结果为同一DD-MM-yyyy格式的字符串:
function addFourMonths(dateString) {
var dateParts = dateString.split('-');
var newDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
newDate.setMonth(newDate.getMonth() + 4);
return newDate.getDate() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getFullYear();
}
要使用:
var myDate = addFourMonths('01-12-2011');
alert('The date is ' + myDate);
结果(live demo):
'The date is 1-4-2012.'
注意,使用setMonth(newmonth)
如果newmonth
当打之年自动递增大于12,所以没有必要测试,由于一些这里介绍做其他的答案。
从MDC docs for setMonth:
“如果指定的参数是在预期范围之外,setMonth尝试更新的Date对象的日期信息。因此例如,如果使用15 monthValue,年份将增加1(年+ 1),3月份将用于月份。“
谢谢埃德加...它帮助我很多... :-)通过使用此代码,我得到了我所需要的..许多谢谢朋友 – Fero 2011-05-09 05:53:22