可可 - 计算两个日期之间的工作日

时间:2014-08-27 10:34:42

标签: objective-c cocoa date nsdate

我是可可编程的新手,我想知道如何获得日期之间的工作日数。所以只在周一到周五。感谢。

1 个答案:

答案 0 :(得分:3)

NSDate *startDate = ...;
NSDate *stopDate = ...;

NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = @"yyyy-MM-dd";
startDate = [df dateFromString:[df stringFromDate:startDate]]; // get start of the day

NSDateComponents *comps = [NSDateComponents new];
comps.day = 1; // one day in NSDateComponents

NSUInteger count = 0;
while ([stopDate timeIntervalSinceDate:startDate] >= 0) {

    NSInteger weekday = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:startDate].weekday;

    if (weekday != 1 && weekday != 6) ++count; // filter out weekend days - 6 and 1

    startDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:startDate options:0]; // increment start day
}