2014-08-27 185 views

回答

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 
} 
+0

你最開始用'NSCalendar'和'NSDateComponents',然後以'3600 * 24'結束。不要用秒來增加天數!不是每天都有24小時,不是每小時都有3600秒。日期和時間是一種痛苦。 – JustSid 2014-08-27 12:18:01

+1

@JustSid,請給出一些直接的例子:「不是每天都有24小時,而不是每小時都有3600秒。」無論如何,謝謝,更新。 – malex 2014-08-27 12:22:35

+0

例如,從夏令時切換到夏令時。閏秒。有時會刪除或添加整個日期以使日曆同步。 – JustSid 2014-08-27 14:08:24

相關問題