Check if date falls between 2 dates

后端 未结 6 1778
栀梦
栀梦 2020-12-08 13:43

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

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

let dateFormatter = NSDateFormatter         


        
6条回答
  •  猫巷女王i
    2020-12-08 14:32

    Swift 2

    For a better answer see Swift ≧ 3.

    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().isBetween(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 isBetween(date date1: NSDate, andDate date2: NSDate) -> Bool {
            return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
        }
    }
    

提交回复
热议问题