If all you want is the number of recurrences, the fastest (constant time regardless of the size of the date range) is to do the following.
Calculate the number of days in the date range. See formula below.
Determine how many recurrences can fit in that number of days. This can be done with a simple division and floor operation. For instance, if the date range has 100 days, and you want a weekly recurrence, the number of recurrences is Math.floor(100 / 7)
It will help if you set the start of your date range to be the date of the first recurrence.
If you want to get the actual dates and also want to do things like excluding weekends or holidays, you need to iterate over the date range as follows.
// psuedo-code
d = start_date;
interval_days = recurrence_days;
n = 0;
while(is_same_day_or_before(d, end_date)) {
if(not_an_excluded_day(d)) {
print(d);
n++;
}
d = add_days(d, interval_days)
}
print("There are " + n + " recurrences");
This approach will let you do things like excluding weekends and holidays, if necessary.
You can implement is_same_day_or_before(d1,d2)
with a simple comparison like d1 <= d2
. If d1
and d2
can be in different time zones, then you want a more sophisticated check that accommodates for day light savings adjustments, etc.
The add_days
function is more straightforward.
function add_days(d,n) {
var d = new Date(d.getTime());
d.setDate(d.getDate() + n);
return d;
}
Calculating the number of dates between two (javascript) dates
The answer here and copied below for reference gives you a fast and accurate way of doing this regardless of how large the date range is.
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}