检查时间是否在Swift范围内

时间:2016-08-17 00:57:35

标签: ios swift

如何在Swift中检查时间是否在下午6点到晚上11点之间?我很难使用NSDateFormatter,我觉得必须有一个更简单的方法。

4 个答案:

答案 0 :(得分:4)

使用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

(自OP状态以来编辑,11PM不应包括在内)

答案 1 :(得分:1)

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

此解决方案适用于用户当前时间。 MST以外的人会使用该应用吗?

答案 2 :(得分:0)

使用NSCalendarNSDateComponents。在Xcode上搜索字符串&#34; Calendrical Calculation。&#34;

您可以从日期中提取小时,分钟和秒,并编写复合if语句以检查时间是否在范围内:

if components.hour >= 18 && components.hour < 23 {
  print("The time is between 6PM and 11PM")
}

答案 3 :(得分:-1)

我假设你开始使用字符串(请添加更多上下文并解释您尝试过的内容或至少下次处理的内容)。

[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
}

或者将其作为&amp;&amp;如果你同时检查两者。