How to get the 'n' weekday of a Date

依然范特西╮ 提交于 2020-01-30 11:47:10

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/39527084/how-to-get-the-n-weekday-of-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!