Cocoa - Calculate working days between two dates

爷,独闯天下 提交于 2019-12-24 08:37:09

问题


I new in cocoa programing and I want to know how I get the number of working days between to dates. So only from Monday to Friday. Thanks.


回答1:


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
}


来源:https://stackoverflow.com/questions/25524895/cocoa-calculate-working-days-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!