如何获取日期的 'n' 工作日

How to get the 'n' weekday of a Date

我需要将这个函数翻译成swift。 基本上是什么得到了当前一周的 'n' 天。因此,例如,如果我将它与 NSDate().getWeekDay(0) 一起使用,它会给我 9 月 11 日星期日,依此类推。 但似乎 rangeOfUnit 不再存在于 Swift-3 中。 这是我之前在 Swift-2

中的实现
extension NSDate {
    func getWeekDay(day: Int) -> NSDate {
        var beginningOfWeek: NSDate?
        NSCalendar.currentCalendar().rangeOfUnit(NSCalendarUnit.WeekOfYear, startDate: &beginningOfWeek, interval: nil, forDate: self)
        let comps = NSDateComponents()
        comps.day = day
        comps.minute = NSCalendar.currentCalendar().component(NSCalendarUnit.Minute, fromDate: self)
        comps.hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: self)
        let nextDate = NSCalendar.currentCalendar().dateByAddingComponents(comps, toDate: beginningOfWeek!, options: .SearchBackwards)
        return nextDate!
    }
}

有一个替代方法可以获取一周的开始时间 直接翻译成 Swift 3:

extension Date {
    func getWeekDay(day: Int) -> Date {
        let cal = Calendar.current
        let comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: self)
        let beginningOfWeek = cal.date(from: comps)!
        let nextDate = cal.date(byAdding: .day, value: day, to: beginningOfWeek)!
        return nextDate
    }
}

这是您在 Swift 3 中针对 Date 的扩展,并进行了一些优化

extension Date {
  func getWeekDay(day: Int) -> Date {
    var beginningOfWeek = Date()
    var interval : TimeInterval = 0
    let currentCalendar = Calendar.current
    currentCalendar.dateInterval(of: .weekOfYear, start: &beginningOfWeek, interval: &interval, for: self)
    return currentCalendar.date(byAdding: .day, value: day, to: beginningOfWeek)!
  }
}

rangeOfUnit(startDate:interval:forDate:)在新的Calendar结构中变成了dateInterval(of:start:interval:for:)