Search code examples
iosarraysnsdate

check if NSDate occur at particular patterns


I am trying to create a calendar app to show events.

Some of these events are recurring events (Daily,Weekly).

Let's say there are two events eventA (weekly),eventB(daily) that are created on Jan 10 2012.

so when the user open the current month calendar, I need to figure out whether these events are to be shown today based on their recurring pattern.

Right now I'm doing in the following way:

Get the event start date

   NSDate * startDate

Generate the offset endnote

   NSDate *offSetEndDate = [startDate dateByAddingYears:10];

I want to show these events for utpo 10 years from their start date

Now add the event occurrence dates to an array:

//Daily
        if (recurring==1) {
            NSDate *nextOccurenceDate = [startDate dateByAddingDays:1];
            BOOL eventCrossedOffSetDate = NO;
            while (eventCrossedOffSetDate == NO) {
                [dateArr addObject:[nextOccurenceDate shortDateString]];
                nextOccurenceDate = [nextOccurenceDate dateByAddingDays:1];
                if (![self isDateValid:nextOccurenceDate andEndDate:offsetEndDate]) {
                    eventCrossedOffSetDate = YES;
                }
            }
        }

This generates an array of dates for the event from its start date to current date.

And I use this array to check if current day/user selected day exists to show/hide the event.

This method just compares two dates.

-(BOOL)isDateValid:(NSDate*)startDate andEndDate:(NSDate*)endDate{

    if ([startDate compare:endDate] == NSOrderedDescending) {
        //"startDate is later than endDate
        return NO;
    } else if ([startDate compare:endDate] == NSOrderedAscending) {
        //startDate is earlier than endDate
        return YES;
    } else {
        //dates are the same
        return YES;

    }

    return NO;
}

This of course does the job, but for more events this is taking too much time to perform calculations and return array.

IS there anything I could do to improve this ?


Solution

  • For the weekly events just check if the weekday of someDate matches that of the event:

    let eventWeekDay  = Calendar.current.component(.weekday, from: event.startDate)
    let todayWeekDay  = Calendar.current.component(.weekday, from: Date())
    
    if todayWeekDay == eventWeekDay
    {
        // Today has the weekly event.
    }