2011-05-07 57 views
0

特此通過添加季月我是以下輸入:如何使用Java腳本

月由分開:4個月

將與年份和月份日期:07- 05-2011。

現在我需要通過使用java腳本或jQuery添加4個月。如何才能做到這一點?

例如:

我有日期爲:2011年1月1日和持續時間是4

我的輸出應爲:

01-12 -2010

01-04-2011

2011年1月8日

01-12-2011

例如,如果它是:

我有日期爲:01-06-2011並且持續時間是4

我的輸出應該是:

01-06-2011

2011年1月10日

01-02-2012

01-06-2012

預先感謝

回答

3

這裏有:

var initialDate = new Date(2011, 5, 1); //Your example number two. January is 0 
for(var i=0; i<4; i++){ 
    var newMonth = initialDate.getMonth() + i; 
    var newYear = initialDate.getYear(); 
    if(newMonth >= 12){ 
    newMonth = newMonth % 12; 
    newYear ++; 
    } 
    var newDate = new Date(newYear, newMonth, 1); 
    alert(newDate); 
} 

希望這有助於。乾杯

+0

謝謝埃德加...它幫助我很多... :-)通過使用此代碼,我得到了我所需要的..許多謝謝朋友 – Fero 2011-05-09 05:53:22

1

甲日期對象具有它接受一個一個的getMonth方法和setMonth方法整數(月數)。

所以,也許一個功能:

function GetNextPeriod(basisDate){ 
    // Copy the date into a new object 
    var basisDate = new Date(basisDate); 
    // get the next month/year 
    var month = basisDate.getMonth() +4; 
    var year = basisDate.getFullYear(); 
    if (month >= 12){ 
    month -= 12; 
    year++; 
    } 
    // set on object 
    basisDate.setMonth(month); 
    basisDate.setFullYear(year); 
    // return 
    return basisDate; 
} 

var period1 = GetNextPeriod(inputDate); 
var period2 = GetNextPeriod(period1); 
var period3 = GetNextPeriod(period2); 
+0

您還需要考慮到幾年的重疊,setMonth需要0-11,而不是幾個月來添加。 – 2011-05-07 14:42:22

+0

好點。 @OP,在這個上運行一些測試會讓你知道 – 2011-05-07 14:46:13

+0

看起來不錯OP .... – 2011-05-07 14:59:18

0

沒有什麼內置到原有的Date對象做任何日期計算這樣的。你可以選擇編寫自己的函數來在4個月內增加毫秒數,或者你可以檢查出DateJS

0

這裏是一個函數,需要一個字符串像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月份將用於月份。「