swift - NSdate 范围总删除周末 Swift

标签 swift range nsdate weekday weekend

我正在制作一个工作假期/假期预订应用程序。 我有一个扩展程序可以计算出 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
    }
}

最佳答案

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

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
}

关于swift - NSdate 范围总删除周末 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33853363/

相关文章:

ios - 在 tableView.deselectRowAtIndexPath 中使用 indexPath 与 indexPath.row

css - 输入范围的 IE 内部刻度

ios - 谷歌日历数据的 NSDateFormatter dateFormat

iphone - 如何创建一个完整的 NSDate 对象来表示下一个指定的日期时间?

ios - 销毁带有烟雾效果的uiimage View

ios - View Controller 的 Swift 方向覆盖

arrays - Matlab:提取(拆分)数组元素的优雅方式

javascript - 如何从 contenteditable 中获取特定选择

iphone - 在 24 小时 iphone 中没有获取日期 whien 时间格式

ios - 调用 TableView 中的最后一个单元格