Hi I am trying to check if the current time is within a time range, say 8:00 - 16:30. My code below shows that I can obtain the current time as a string, but I am unsure how I can use this value to check if it is inside the time range specified above. Any help would be greatly appreciated!
var todaysDate:NSDate = NSDate()
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
var dateInFormat:String = dateFormatter.stringFromDate(todaysDate)
println(dateInFormat) // 23:54
Swift 3
This is a function that returns a String by comparing if the current time is within a range of given times. Run it in a Playground and adapt it to your own needs.
}
Here is some code I use in one of my current projects. Just set start time as 8:00, end time as 16:30, and timeStamp as current time.
In Swift 3.0 you can use the new Date value type and compare directly with ==,>,< etc
Very handy indeed.
You can use the
compare
method fromNSDate
: it will return anNSComparisonResult
(OrderedSame
,OrderedAscending
orOrderedDescending
) that you can check against your start and end dates:You could make
NSDate
conform to theComparable
protocol to be able to use the==
,!=
,<=
,>=
,>
and<
operators. For example:To use this to check a date was within two dates you could use:
Here are a few more examples of how to use the operators with
NSDate
:There are lots of ways to do this. Personally, I don't like working with strings if I can avoid it. I'd rather deal with date components.
Below is some playground code that uses a Calendar object to get the day/month/year of the current date, and adds the desired hour/minute components, and then generates a date for those components.
It creates dates for 8:00 and 16:30, and then compares the dates to see if the current date/time falls in that range.
It's longer than other people's code, but I think it's worth learning how to do calculations with dates using a Calendar:
EDIT #3:
This answer is from a long time ago. I'll leave the old answer below, but here is the current solution:
@CodenameDuchess' answer uses a system function,
date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)
Using that function, the code can be simplified to this:
The old (Swift 2) answer follows, for historical completeness:
EDIT:
The code in this answer has changed a LOT for Swift 3.
Instead of using
NSDate
, it makes more sense to us the nativeDate
object, andDate
objects areEquatable
andComparable
"out of the box".Thus we can get rid of the
Equatable
andComparable
extensions and the definitions for the<
,>
and=
operators.Then we need to do a fair amount of tweaking of the syntax in the
dateAt
function to follow Swift 3 syntax. The new extension looks like this in Swift 3:Swift 3 version: