【问题标题】:NSdate range total removing weekends SwiftNSdate 范围总计删除周末 Swift
【发布时间】:2016-02-24 12:22:39
【问题描述】:

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

【问题讨论】:

    标签: swift range nsdate weekday weekend


    【解决方案1】:

    我找到了这个。它计算出 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-13
      • 2013-03-01
      • 2023-02-08
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      相关资源
      最近更新 更多