Reputation:
How can I check if the time is between 6PM and 11PM MST in Swift? I am having a hard time using the NSDateFormatter, and I feel there must be an easier way.
Upvotes: 1
Views: 2454
Reputation: 666
I begin with a string as I assume you do (please add more context and explain what you've tried or at least what you're dealing with next time).
[Swift 3]
// example of a date-time string
let timeSubstring = "2016-08-06T18:16:11"
// initialize
let datetimeTime = DateFormatter()
// provide format
datetimeTime.dateFormat = "yyyy-MM-ddEEEEEHH:mm:ss"
// converting from time zone
datetimeTime.timeZone = TimeZone(identifier: "MST")
// DateFormatter has been set up, now we can form the date properly
let formDate = datetimeTime.date(from: timeSubstring)
// create your upper and lower bounds ( fill in )
let topDate = datetimeTime.date(from: "XXXX-XX-XXXXX:XX:XX")
let bottomDate = datetimeTime.date(from: "XXXX-XX-XXXXX:XX:XX")
// make comparisons
// checks condition left operand is smaller than right operand
if formDate?.compare(other: topDate) == .orderedAscending {
// some code
}
// condition right smaller than left
if formDate?.compare(other: bottomDate) == .orderedDescending {
// some code
}
Or make it an && if you're checking both simultaneously.
Upvotes: -1
Reputation: 93191
Use NSCalendar
:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(name: "MST")!
let hour = calendar.component(.Hour, fromDate: date)
let between6And11PM = 18 <= hour && hour < 23
(edited since the OP states 11PM shouldn't be included)
Upvotes: 6
Reputation: 166
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute], fromDate: date)
let hour = components.hour
switch hour {
case 18...23:
print("True")
default:
print("False")
}
This solution works for the user's current time. Will people outside of MST be using the app?
Upvotes: 2
Reputation: 131491
Use NSCalendar
and NSDateComponents
. Do a search in Xcode on the string "Calendrical calculations."
You could extract the hours, minutes, and seconds from the date and write a compound if statement to check to see if the time is in range:
if components.hour >= 18 && components.hour < 23 {
print("The time is between 6PM and 11PM")
}
Upvotes: 0