I’m having trouble with recurring events in my calendar app. Events that repeat several days within a week and extend over several weeks appear sporadically. Could someone help me understand why events are sometimes missing during certain weeks?
This is the function that is responsible for obtaining the events:
async function getCalendarEvents(accessToken) {
// Get events from Microsoft Graph API calendar
const response = await fetch('https://graph.microsoft.com/v1.0/me/events', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
// Handle error case when fetching calendar events
const errorText = await response.text();
console.error(`Error fetching calendar events: ${response.status} ${response.statusText}`, errorText);
throw new Error('Error fetching calendar events');
}
const data = await response.json();
const events = [];
// Function to adjust time to local timezone (Spain)
function adjustToLocalTime(dateTime) {
const date = new Date(dateTime);
const timeZoneOffset = date.getTimezoneOffset() * 60000; // Convert minutes to milliseconds
const localDate = new Date(date.getTime() - timeZoneOffset);
return new Date(localDate.getTime() + (60 * 60 * 1000)).toISOString(); // Adjust to CEST/CET
}
// Process recurring events
const recurringEvents = data.value.filter(event => event.recurrence && event.recurrence.pattern);
recurringEvents.forEach(event => {
const startDate = new Date(event.start.dateTime);
const endDate = new Date(event.end.dateTime);
const recurrence = event.recurrence.pattern;
let nextInstance = new Date(startDate);
let instanceDate = new Date(startDate);
let count = 0;
const endRecurrenceDate = event.recurrence.range && event.recurrence.range.endDate ? new Date(event.recurrence.range.endDate) : null;
while (count < 100) {
if (!recurrence.daysOfWeek) {
// If no specific days of the week, add event instance
events.push({
title: event.subject,
start: adjustToLocalTime(nextInstance.toISOString()),
end: adjustToLocalTime(new Date(nextInstance.getTime() + (endDate.getTime() - startDate.getTime())).toISOString()),
allDay: event.isAllDay
});
// Calculate next instance based on recurrence pattern
switch (recurrence.type) {
case "daily":
nextInstance.setDate(nextInstance.getDate() + recurrence.interval);
break;
case "absoluteMonthly":
nextInstance.setMonth(nextInstance.getMonth() + recurrence.interval);
break;
case "absoluteYearly":
nextInstance.setFullYear(nextInstance.getFullYear() + recurrence.interval);
break;
}
// Check if next instance exceeds recurrence end date
if (endRecurrenceDate && nextInstance > endRecurrenceDate) {
break;
}
count++;
continue;
}
// If event occurs on specific days of the week, check if it matches
const daysOfWeek = recurrence.daysOfWeek.map(day => {
switch (day.toLowerCase()) {
case "monday": return "lunes";
case "tuesday": return "martes";
case "wednesday": return "miércoles";
case "thursday": return "jueves";
case "friday": return "viernes";
case "saturday": return "sábado";
case "sunday": return "domingo";
}
});
daysOfWeek.forEach(day => {
// Adjust instanceDate to the next specified day of the week
while (instanceDate.getDay() !== ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"].indexOf(day)) {
instanceDate.setDate(instanceDate.getDate() + 1);
}
// If instanceDate is within range and valid instance, add the event
if (instanceDate >= startDate && (!endRecurrenceDate || instanceDate <= endRecurrenceDate)) {
events.push({
title: event.subject,
start: adjustToLocalTime(instanceDate.toISOString()),
end: adjustToLocalTime(new Date(instanceDate.getTime() + (endDate.getTime() - startDate.getTime())).toISOString()),
allDay: event.isAllDay
});
}
});
// Move instanceDate to the start of the next week based on recurrence interval
instanceDate.setDate(instanceDate.getDate() + 1);
instanceDate.setDate(instanceDate.getDate() + (7 - instanceDate.getDay()));
// Check if instanceDate exceeds recurrence end date
if (instanceDate > endRecurrenceDate) {
break;
}
count++;
}
});
// Process individual events (non-recurring)
const singleEvents = data.value.filter(event => !event.recurrence);
singleEvents.forEach(event => {
events.push({
title: event.subject,
start: adjustToLocalTime(event.start.dateTime),
end: adjustToLocalTime(event.end.dateTime),
allDay: event.isAllDay
});
});
// Print processed events to console for debugging
console.log("Processed events FINAL:", events);
// Return processed events
return events;
}
As seen in the images, the event called “loko” repeats every Tuesday, Wednesday and Sunday for 4 weeks, however in my web calendar only the first and third weeks are shown
thanks a lot!!