3

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.

4

2 回答 2

6

以下代码的想法是计算开始日期之后给定工作日的第一次出现,然后计算距离结束日期剩余的周数。

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;
}

(代码假设一周有 7 天,这对于公历是正确的。如有必要,代码可能会推广到与任意日历一起使用。)

于 2013-07-30T11:48:10.900 回答
0
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:[NSDate date]];
//pass different date in fromDate and toDate column.
于 2013-07-30T11:05:22.463 回答