我必须在Javascript中使用重复日期。例如,给定一个表示11月24日的字符串(--11-24
),我希望将来能够获得此重复日期的下一个出现指定的时刻。
referencePoint = someLibraryForRecurringDates.referencePoint("1985-01-02");
nextOccurence = referencePoint.getNextOccurenceOf("--11-24");
// nextOccurence is a Date representing "1985-11-24"
是否有一个Javascript库可以处理重复日期的不那么重要的域名?
答案 0 :(得分: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"
闰年等将自动得到尊重。