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



如何找到发生在两个NSDates之间的特定工作日的计数?

我已经搜索了很长一段时间,但找到了唯一的解决方案,即计算工作日的总数,而不仅仅是一个特定的工作日。

以下代码的思想是计算给定开始日期后的工作日,然后计算剩余周数到结束日期。

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

(该代码假设一周有七天,公历也是如此。如果有必要,代码可能会被泛化为使用任意日历。)

NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:[NSDate date]];
//pass different date in fromDate and toDate column.

最新更新