0

我正在制作一个工作假期/假期预订应用程序。我有一个扩展程序可以计算 2 个 NSDates 之间的总天数,效果很好,但我不知道如何从总数中删除所有周末天数。

你能帮忙吗?

extension NSDate {
    func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone     timeZone: NSTimeZone? = nil) -> Int {
        let calendar = NSCalendar.currentCalendar()
        if let timeZone = timeZone {
            calendar.timeZone = timeZone
        }
        var startDate: NSDate?, endDate: NSDate?
        calendar.rangeOfUnit(.Day, startDate: &startDate, interval: nil, forDate: self)
        calendar.rangeOfUnit(.Day, startDate: &endDate, interval: nil, forDate: toDateTime)
        let difference = calendar.components(.Day, fromDate: startDate!, toDate: endDate!, options: [])
        return difference.day
    }
}
4

1 回答 1

4

我找到了这个。它计算出 2 个 NSDates 之间的周末天数

func numberOfWeekendsBeetweenDates(startDate startDate:NSDate,endDate:NSDate)->Int{
    var count = 0
    let oneDay = NSDateComponents()
    oneDay.day = 1;
    // Using a Gregorian calendar.
    let calendar = NSCalendar.currentCalendar()
    var currentDate = startDate;
    // Iterate from fromDate until toDate
    while (currentDate.compare(endDate) != .OrderedDescending) {
       let dateComponents = calendar.components(.Weekday, fromDate: currentDate)
        if (dateComponents.weekday == 1 || dateComponents.weekday == 7 ) {
            count++;
        }
        // "Increment" currentDate by one day.
        currentDate = calendar.dateByAddingComponents(oneDay, toDate: currentDate, options: [])!
    }
    return count
}
于 2015-11-22T16:51:01.540 回答