I am trying to figure out whether or not the current date falls within a date range using NSDate.
For example, you can get the current date/time using NSDate:
NSDate rightNow = [NSDate date];
I would then like to use that date to check if it is in the range of 9AM - 5PM.
With Swift 4.2 and iOS 12, you can use one of the two solutions below in order to check if a date occurs between two other dates.
#1. Using
DateInterval
'scontains(_:)
methodDateInterval
has a method calledcontains(_:)
.contains(_:)
has the following declaration:The following Playground code shows how to use
contains(_:)
in order to check if a date occurs between two other dates:#2. Using
ClosedRange
'scontains(_:)
methodClosedRange
has a method calledcontains(_:)
.contains(_:)
has the following declaration:The following Playground code shows how to use
contains(_:)
in order to check if a date occurs between two other dates:Continuing with Quinn's and Brock´s solutions, is very nice to subclass NSDate implementation, so it can be used everywhere like this:
And at any part of your code you can use it as:
(myNSDate, thisNSDate and thatNSDate are of course NSDates :)
A better version in Swift:
There is better and more swifty solution for this problem.
Then you can call it like this.
Even you can pass date random as this extension checks which one is minimum and which one in not.
you can use it in swift 3 and above.