Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 802
moxmlb Avatar asked Nov 18 '16 10:11

moxmlb


2 Answers

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")
like image 85
Nirav D Avatar answered Sep 30 '22 01:09

Nirav D


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
}
like image 31
Sapana Ranipa Avatar answered Sep 30 '22 02:09

Sapana Ranipa