Exceptions Exceptions - 21 days ago 8
Swift Question

Check if date falls between 2 dates

I have this code where convert a String into a date object

let date2 = KeysData[indexPath.row]["starttime"] as? String

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

if let date = dateFormatter.dateFromString(date2!) {
println(date)
}


I would like to know if the current date falls between the 2 days i got in the array
startdate
and
endate

Answer

You already have the code for conversion of your date string in KeysData to NSDate. Assuming you have the two dates in startdate and enddate, all you have to do is check if the current date is in between:

let startdate = ...
let enddate = ...

NSDate().isBetweeen(date: startdate, andDate: enddate)

extension NSDate {
    func isBetweeen(date date1: NSDate, andDate date2: NSDate) -> Bool {
        return date1.compare(self) == self.compare(date2)
    }
}

Edit: If you want to perform an inclusive range check, use this condition:

 extension NSDate {
    func isBetweeen(date date1: NSDate, andDate date2: NSDate) -> Bool {
        return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
    }
}