1

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

Community
  • 1
  • 1
Dave G
  • 12,042
  • 7
  • 57
  • 83
  • Your "Swift 2" version is not valid Swift 2 code, and firstWeekday is not a calendar component. – Martin R Sep 05 '16 at 20:43
  • 1
    [Swift days between two NSDates](http://stackoverflow.com/questions/24723431/swift-days-between-two-nsdates) has code for all Swift versions up to Swift 3: http://stackoverflow.com/a/38549470/1187415. – Martin R Sep 05 '16 at 20:45
  • 1
    I have also updated the original question o Xcode 8 beta 6 http://stackoverflow.com/a/27184261/2303865 – Leo Dabus Sep 05 '16 at 21:59
  • In response to @MartinR, at some point in the Xcode 8 betas, the migration assistant changed the old `weekComponent` to `firstWeekday` instead of `weekday` as it should have. Caused me more confusion than it should have. – jjatie Oct 30 '16 at 14:34

1 Answers1

3

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)
Rob
  • 415,655
  • 72
  • 787
  • 1,044