在我的旧代码中,我有一个名为“daysFrom”的Date扩展名,我似乎无法迁移到Swift 3:
func daysFrom(_ date:Date) -> Int{
//Swift 2:
//return Calendar.current.date(.firstWeekday, from: date, to: self, options: []).day
//My Swift 3 attempt, doesn't work:
return Calendar.current.date([.firstWeekday], from: date, to: self).day
}
我发现this Swift线程说:
...... Swift 2中的NSCalendarUnit和Swift 3中的Calendar.Component都不包含第一周的组件......
那么如何替换此扩展名?
答案 0 :(得分:3)
要获得两个日期之间的天数,请使用dateComponents
:
extension Date {
func days(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day!
}
}
然后
let days = endDate.days(from: startDate)