简体   繁体   中英

How to get the 'n' weekday of a Date

I need to translate this function into swift. Basically what does it get the 'n' day of the current week. So for example if i use it with NSDate().getWeekDay(0) it gives me Sun 11 Sept, and so on. But seems rangeOfUnit no longer exists in Swift-3. This was my previous implementation in 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!
    }
}

There is an alternative to get the start of the week which translates directly to 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
    }
}

This is your extension in Swift 3 for Date and a bit optimized

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:) has been turned into dateInterval(of:start:interval:for:) in the new Calendar structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM