Within my program, users can set events with start and end dates, as well as the period of repetition: weekly, monthly by date, monthly by weekday, or yearly. Once an event is created, it's stored in the database and displayed on the main calendar page.
I've successfully implemented algorithms for repeating events weekly, monthly by date, and yearly. However, I'm facing a challenge with monthly repetition based on weekdays. This refers to events that occur on the same weekday each month between the specified start and end dates.
For instance, an event might repeat on the first Monday of every month from March 1st to November 1st. The goal is to generate dates like April 5th (the first Monday in April) and continue this pattern until November.
The function below handles monthly repetition by date for events occurring on the 15th of any month:
function repeatEventMonthly(jsonArray, num){
// Extracting start and end dates from JSON and creating Date objects
var split = jsonArray[num].Fecha.split("/");
var split2 = jsonArray[num].fechaFin.split("/");
var dd = split[1];
var mm = split[0];
var yy = split[2];
var dd2 = split2[1];
var mm2 = split2[0];
var yy2 = split2[2];
var starDate = new Date();
var endDate = new Date();
starDate.setFullYear(yy);
starDate.setMonth(mm-1);
starDate.setDate(dd);
endDate.setFullYear(yy2);
endDate.setMonth(mm2-1);
endDate.setDate(dd2);
// Calculating days between start and end date
var top = getDaysInDates(starDate, endDate);
if (jsonArray[num].tipoRepeticion == "2") {
// Handling Monthly by Weekday
}else if(jsonArray[num].tipoRepeticion == "3"){
// Generating dates for Monthly by Date
for (let index = 0; index < top; index++) {
let sd = new Date(starDate);
sd.setDate(sd.getDate()+index);
if (sd.getDate() == starDate.getDate()) {
let str = ((sd.getMonth()+1) + "/" + sd.getDate() + "/" + sd.getFullYear()).toString();
eventMen.push({
date: constructDates(str, 0, jsonArray[num].tipoRepeticion),
title: jsonArray[num].titulo,
descripcion: jsonArray[num].descripcion,
tipo: jsonArray[num].tipo,
tipoRepeticion : jsonArray[num].tipoRepeticion
});
}
}
}
This function effectively generates events one month apart on the same date, such as repeating an event on the 3rd of each month between March and December. While I have tackled other types of recurring dates successfully, calculating monthly repetition by weekday poses a greater challenge due to varying month lengths. For example, determining the "first Monday of a month" requires more complex logic compared to fixed-date repetitions. Any suggestions or solutions on how to address this issue would be greatly appreciated. Additionally, there are various scenarios for monthly recurrence, not just limited to the "first Monday" but also involving the second Tuesday or last Friday of each month.