Swift 3 日期扩展:获取 'daysFrom' 一个日期

Swift 3 Date Extension: Getting 'daysFrom' a date

在我的旧代码中,我有一个名为 "daysFrom" 的日期扩展,我似乎无法迁移到 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
}

我发现 Swift 帖子说:

...neither NSCalendarUnit in Swift 2 nor Calendar.Component in Swift 3 contain the components firstWeekday...

那么如何替换这个扩展?

要获取两个日期之间的天数,请使用 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)