Reputation: 385
I am getting recurrence pattern from microsoft graph api . I need to generate dates in code on the basis of recurrence pattern details which it gives me.
This is the pattern which I am getting
"recurrence": {
"pattern": {
"type": "relativeMonthly",
"interval": 1,
"month": 0,
"dayOfMonth": 0,
"daysOfWeek": [
"wednesday"
],
"firstDayOfWeek": "sunday",
"index": "third"
},
"range": {
"type": "endDate",
"startDate": "2023-12-20T00:00:00.000Z",
"endDate": "2024-12-20T23:59:00.000Z",
"recurrenceTimeZone": "India Standard Time",
"numberOfOccurrences": 0
}
}
this is my code
case "relativeMonthly":
if (pattern.daysOfWeek && pattern.daysOfWeek.length > 0) {
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
var day = days.indexOf(dayName.toLowerCase());
var nextOccurrence = findNthDayOfMonth(newDate.getFullYear(), newDate.getMonth(), day, pattern.index);
newDate = new Date(nextOccurrence);
} else {
newDate.setMonth(newDate.getMonth() + pattern.interval);
}
break;
function findNthDayOfMonth(year, month, dayOfWeek, nthOccurrence) {
// Create a date object at the beginning of the target month
let date = new Date(year, month, 1);
// Find the first occurrence of the day of the week
let firstDayOccurrence = (7 + dayOfWeek - date.getDay()) % 7;
date.setDate(date.getDate() + firstDayOccurrence);
// Adjust to the nth occurrence
let daysToAdd = (nthOccurrence - 1) * 7;
date.setDate(date.getDate() + daysToAdd);
return date;
}
my code is not giving me correct dates here for example for above pattern the date should be 20th june 2024 but its giving me 17th june which should not be the case here and it is giving me wrong dates constantly.
Need help with correct code.
Upvotes: 0
Views: 81