如何找到两个NSDates
之间发生的特定工作日的计数?
我已经搜索了很长一段时间,但却想出了一个解决方案,其中计算了整个工作日的数量,而不仅仅是一个特定的工作日。
答案 0 :(得分: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;
}
(该代码假定一周有七天,这对于公历是正确的。 如有必要,代码可能会推广到使用任意日历。)
答案 1 :(得分:0)
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:[NSDate date]];
//pass different date in fromDate and toDate column.