一个月中的周末天数

Number of weekend days in a month

如何获得一个月或两个 NSDate 之间的周末数? 我试着用

做一些技巧
 calendar.components( NSCalendarUnit.WeekCalendarUnit, fromDate: startDate, toDate: endDate, options: nil) 

但是没有结果

NSInteger count = 0;
NSInteger saturday = 7;

// Set the incremental interval for each interaction.
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];

// Using a Gregorian calendar.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *currentDate = fromDate;

// Iterate from fromDate until toDate
while ([currentDate compare:toDate] == NSOrderedAscending) {

    NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:currentDate];

    if (dateComponents.weekday == saturday) {
        count++;
    }

    // "Increment" currentDate by one day.
    currentDate = [calendar dateByAddingComponents:oneDay
                                            toDate:currentDate
                                           options:0];
}

NSLog(@"count = %d", count);

根据 TENSRI,我在 swift 中编写代码并进行了一些修复

func numberOfWeekdaysBeetweenDates(#startDate:NSDate,endDate:NSDate)->Int{
    var count = 0
    var oneDay = NSDateComponents()
    oneDay.day = 1;
    // Using a Gregorian calendar.
    var calendar = NSCalendar.currentCalendar()

    var currentDate = startDate;
    // Iterate from fromDate until toDate
    while (currentDate.compare(endDate) != .OrderedDescending) {

        var dateComponents = calendar.components(.WeekdayCalendarUnit, fromDate: currentDate)
        if (dateComponents.weekday == 1 || dateComponents.weekday == 7 ) {
            count++;
        }

        // "Increment" currentDate by one day.
        currentDate = calendar.dateByAddingComponents(oneDay, toDate: currentDate, options: nil)!
    }

    return count
}