Search code examples
iosswiftnsdateswift3nscalendar

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!
    }
}

Solution

  • 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
        }
    }