Search code examples
iosobjective-cdatecocoansdate

Cocoa - Calculate working days between two dates


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.


Solution

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