的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"
闰年和这样会自动得到尊重。
https://github.com/jkbr/rrule - NB,在[chat] – 2013-04-30 21:43:14
中最好问这个问题,年复发对我来说听起来相当微不足道。或者你问的是更普遍的选择? – Bergi 2013-05-01 01:13:11
@Bergi例如,2月29日的生日会怎么样。或者回答一个问题,例如“2013-06-20,这是” - 01-17“最接近的周年纪念日。周年计算有一些重要的细节,我猜想最好使用经过验证的库写我自己的。 – Abdull 2013-05-01 11:55:44