Search code examples
swift3nscalendar

Swift 3 Date Extension: Getting 'daysFrom' a date


In my old code I had a Date extension called "daysFrom" and I can't seem to migrate to 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
}

I found this Swift thread which says:

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

So how do I replace this extension??


Solution

  • To get days between two dates, use dateComponents:

    extension Date {
        func days(from date: Date) -> Int {
            return Calendar.current.dateComponents([.day], from: date, to: self).day!
        }
    }
    

    And then

    let days = endDate.days(from: startDate)