How the recurrence actually works is not a question. I want to implement a way to calculate the days between two dates with a specified recurrence interval. That could be weekly, monthly, bi-monthly(which I don't exactly know about) yearly etc. The simplest thing I have done until now is the following which let me count all the days between two dates and then loop through them with an interval of seven days for weekly recurrence. I would be grateful if you can suggest me the better and correct implementation of it. Thanks.
//Push in the selected dates in the selected array.
for (var i = 1; i < between.length; i += 7) {
selected.push(between[i]);
console.log(between[i]);
}
This function gives a date for every [interval] and [intervalType] (e.g. every 1 month) between two dates. It can also correct dates in weekends, if necessary. Is that what you had in mind?
Here a jsFiddle demo.
function recurringDates(startDate, endDate, interval, intervalType, noweekends) {
intervalType = intervalType || 'Date';
var date = startDate;
var recurrent = [];
var setget = {set: 'set'+intervalType, get: 'get'+intervalType};
while (date < endDate) {
recurrent.push( noweekends ? noWeekend() : new Date(date) );
date[setget.set](date[setget.get]()+interval);
}
// add 1 day for sunday, subtract one for saturday
function noWeekend() {
var add, currdate = new Date(date), day = date.getDay();
if (~[6,0].indexOf(day)) {
currdate.setDate(currdate.getDate() + (add = day == 6 ? -1 : 1));
}
return new Date(currdate);
}
return recurrent;
}
Does this do something like what you're expecting? It would require an explicit argument for the number of days in the interval:
// startDate: Date()
// endDate: Date()
// interval: Number() number of days between recurring dates
function recurringDates(startDate, endDate, interval) {
// initialize date variable with start date
var date = startDate;
// create array to hold result dates
var dates = [];
// check for dates in range
while ((date = addDays(date, interval)) < endDate) {
// add new date to array
dates.push(date);
}
// return result dates
return dates;
}
function addDays(date, days) {
var newDate = new Date(date);
newDate.setDate(date.getDate() + days);
return newDate;
}
var startDate = new Date(2015, 0, 1);
var endDate = new Date(2016, 0, 1);
var interval = 20;
console.log(recurringDates(startDate, endDate, interval));
Here's the example on JSFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With