Check if date falls between 2 dates
extension Date
{
func isBetween(startDate:Date, endDate:Date)->Bool
{
return (startDate.compare(self) == .orderedAscending) && (endDate.compare(self) == .orderedDescending)
}
}
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
}
}
For Swift 4.2+ I used this extension based on answer above:
extension Date {
func isBetween(_ date1: Date, and date2: Date) -> Bool {
return (min(date1, date2) ... max(date1, date2)) ~= self
}
}
But be careful. If this extension doesn't include your start date (date1), then check the time of your dates. May be you'll need to cut the time from dates to fix it. For example, like this:
let myDateWithoutTime = Calendar.current.startOfDay(for: myDate)
Swift ≧ 3
Swift 3 makes this a lot easier.
let fallsBetween = (startDate ... endDate).contains(Date())
Now that NSDate
is bridged to the value type Date
and Date
conforms to Comparable
we can just form a ClosedRange<Date>
and use the contains
method to see if the current date is included.
Caveat: endDate
must be greater or equal startDate
. Otherwise the range could not be formed and the code would crash with a fatalError
.
This is safe:
extension Date {
func isBetween(_ date1: Date, and date2: Date) -> Bool {
return (min(date1, date2) ... max(date1, date2)).contains(self)
}
}