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)
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")
Try This One
let startDateComparisionResult:ComparisonResult = currentDate.compare(clickedDate! as NSDate)
if startDateComparisionResult == ComparisonResult.orderedAscending
{
    // Current date is smaller than end date.
}
else if startDateComparisionResult == ComparisonResult.orderedDescending
{
    // Current date is greater than end date.
}
else if startDateComparisionResult == ComparisonResult.orderedSame
{
    // Current date and end date are same
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With