I have this code where convert a String into a date object
let date2 = KeysData[indexPath.row][\"starttime\"] as? String
let dateFormatter = NSDateFormatter
extension Date {
func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
return date1.timeIntervalSince1970 < self.timeIntervalSince1970 && date2.timeIntervalSince1970 > self.timeIntervalSince1970
}
}
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)
extension Date
{
func isBetween(startDate:Date, endDate:Date)->Bool
{
return (startDate.compare(self) == .orderedAscending) && (endDate.compare(self) == .orderedDescending)
}
}
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)
}
}
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
}
}
None of the answers here explicitly cover the potentially more precise boundary tests which differ between the start and the end.
e.g. An event which starts at 0900 and ends at 1000 should have cases which return the following results:
08:59:59 false
09:00:00 true
09:59:59 true
10:00:00 false
If this is your desired outcome then the following extension will work for you:
extension Date {
func isBetween(_ startDate: Date, and endDate: Date) -> Bool {
return startDate <= self && self < endDate
}
}