我需要将此功能翻译成swift。 基本上它是什么让它得到了' n'本周的一天。因此,例如,如果我将它与NSDate()。getWeekDay(0)一起使用,它会给我9月21日,等等。 但似乎在Swift-3中不再存在rangeOfUnit。 这是我之前在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! } }
答案 0 :(得分:4)
有一个替代方案可以获得本周的开始 直接翻译为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
}
}
答案 1 :(得分:3)
这是你在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:)
已在新dateInterval(of:start:interval:for:)
结构中变为Calendar
。