2013-04-30 66 views
0

我必須在Javascript中使用重複日期。例如,給定一個表示11月24日的字符串(--11-24),我希望在未來從指定的時間點獲得此這個10的重複日期的下一個。使用重複日期,例如週年紀念日,使用Javascript的生日

referencePoint = someLibraryForRecurringDates.referencePoint("1985-01-02"); 
nextOccurence = referencePoint.getNextOccurenceOf("--11-24"); 
// nextOccurence is a Date representing "1985-11-24" 

有哪些治療的重複日期不那麼平凡域Javascript庫?

+1

https://github.com/jkbr/rrule - NB,在[chat] – 2013-04-30 21:43:14

+0

中最好問這個問題,年復發對我來說聽起來相當微不足道。或者你問的是更普遍的選擇? – Bergi 2013-05-01 01:13:11

+0

@Bergi例如,2月29日的生日會怎麼樣。或者回答一個問題,例如「2013-06-20,這是」 - 01-17「最接近的週年紀念日。週年計算有一些重要的細節,我猜想最好使用經過驗證的庫寫我自己的。 – Abdull 2013-05-01 11:55:44

回答

1

Date object會做出這樣的計算很簡單:

// helpers: 
Date.fromString = function(s) { 
    s = s.match(/^(\d{4})-(\d\d?)-(\d\d?)$/); 
    return new Date(s ? Date.UTC(+s[1], s[2]-1, +s[3]) : NaN); 
}; 
Date.prototype.toDate = function() { 
    return this.getUTCFullYear()+"-"+("0"+(this.getUTCMonth()+1)).slice(-2)+"-"+("0"+this.getUTCDate()).slice(-2); 
}; 

function getNextOccurence(referenceDate, desc) { 
    desc = desc.match(/^--(\d\d?|-)-(\d\d?)$/); 
    var next = new Date(referenceDate); 
    if (!desc) return next; 
    next.setUTCDate(+desc[2]); 
    if (next < referenceDate) // if date is smaller than before 
     next.setUTCMonth(next.getUTCMonth()+1); // advance month 
    if (desc[1] != "-") { 
     next.setUTCMonth(desc[1]-1); 
     if (next < referenceDate) // if month is smaller than before 
      next.setUTCFullYear(next.getUTCFullYear()+1); // advance year 
    } 
    return next; 
} 

// Tests: 
> getNextOccurence(Date.fromString("1985-01-02"), "--11-24").toDate() 
"1985-11-24" 
> getNextOccurence(Date.fromString("2012-01-01"), "--02-29").toDate() 
"2012-02-29" 
> getNextOccurence(Date.fromString("2013-01-01"), "--02-29").toDate() 
"2013-03-01" 
> getNextOccurence(Date.fromString("2013-06-20"), "--01-17").toDate() 
"2014-01-17" 

閏年和這樣會自動得到尊重。

相關問題