這裏是一個函數,需要一個字符串像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