该Date
对象将使此类计算变得容易:
// 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"
闰年等将自动得到尊重。