简体   繁体   中英

Check if time is within a range Swift

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.

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)

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?

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")
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM