0

我必须使用 Javascript 中的重复日期。例如,给定一个表示 11 月--11-2424字符串(

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

是否有一个 Javascript 库可以处理不那么平凡的重复日期域?

4

1 回答 1

1

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"

闰年等将自动得到尊重。

于 2013-05-01T12:56:27.653 回答