How can i compare two dates (NSDate) in Swift 3 and get the days between them?

moxmlb picture moxmlb · Nov 18, 2016 · Viewed 12.2k times · Source

How can I compare two dates in Swift 3? I found many solutions for other Swift versions, but they doesn't work for me.

let clickedDay:String = currentcell.DayLabel.text!
    let currentDate = NSDate()
    let currentDay = "" //want the current day
    let dateFormatter = DateFormatter()        
    var dateAsString = ""        
    if Int(clickedDay)! < 10 {            
        dateAsString = "0" + clickedDay + "-11-2016 GMT"
    }
    else {            
        dateAsString = clickedDay + "-11-2016 GMT"
    }

    dateFormatter.dateFormat = "dd-MM-yyyy zzz"
    let clickedDate = dateFormatter.date(from: dateAsString)        
    if currentDate as Date >= clickedDate! as Date {

        return true
    }
    else {
        //Want to get the days between the currentDate and clickedDate
        let daysLeft = ""
    }

I compare the tow dates, but i want the days which are between that tow dates. Can someone help me pls? Thanks and greets

Added: If I have the date 22.11.2016 and the currentdate (now 18.11.2016) i want the days between that (in this case 4)

Answer

Nirav D picture Nirav D · Nov 18, 2016

Simply make extension of Date like this and get difference in days.

extension Date {
    func daysBetweenDate(toDate: Date) -> Int {
        let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
        return components.day ?? 0
    }
}

Now use this extension like this

let numOfDays = fromDate.daysBetweenDate(toDate: toDate)

You can use DateFormatter to convert String to Date like this.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: "18-11-2016")