在两个NSDates之间发生的特定工作日的计数

Dem*_*991 2 cocoa cocoa-touch date objective-c nscalendar

我怎样才能找到两个特定工作日的计数NSDates

我已经搜索了很长一段时间,但只提出了一个解决方案,其中计算了整个工作日的数量,而不仅仅是一个特定的工作日.

Mar*_*n R 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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 上面提到的泛化应该就像用`[cal rangeOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:fromDate]`替换hard 7一样简单. (2认同)