Question

How can I find the count of a specific weekday occurring between two NSDates?

I have searched for quite a while but came up with only solution in which number of total weekdays have been counted, not only the one specific week day.

Was it helpful?

Solution

The idea of the following code is to compute the first occurrence of the given weekday after the start date, and then compute the number of weeks remaining to the end date.

NSDate *fromDate = ...;
NSDate *toDate = ...;
NSUInteger weekDay = ...; // The given weekday, 1 = Sunday, 2 = Monday, ...
NSUInteger result;

// Compute weekday of "fromDate":
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *c1 = [cal components:NSWeekdayCalendarUnit fromDate:fromDate];

// Compute next occurrence of the given weekday after "fromDate":
NSDateComponents *c2 = [[NSDateComponents alloc] init];
c2.day = (weekDay + 7 - c1.weekday) % 7; // # of days to add
NSDate *nextDate = [cal dateByAddingComponents:c2 toDate:fromDate options:0];

// Compare "nextDate" and "toDate":
if ([nextDate compare:toDate] == NSOrderedDescending) {
    // The given weekday does not occur between "fromDate" and "toDate".
    result = 0;
} else {
    // The answer is 1 plus the number of complete weeks between "nextDate" and "toDate":
    NSDateComponents *c3 = [cal components:NSWeekCalendarUnit fromDate:nextDate toDate:toDate options:0];
    result = 1 + c3.week;
}

(The code assumes that a week has seven days, which is true for the Gregorian calendar. If necessary, the code could probably generalized to work with arbitrary calendars.)

OTHER TIPS

NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:[NSDate date]];
//pass different date in fromDate and toDate column.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top