Ios NSComparisonResult在晚上10点及以上时间未按预期工作

Ios NSComparisonResult在晚上10点及以上时间未按预期工作,ios,swift,datetime-comparison,Ios,Swift,Datetime Comparison,我需要在Swift中比较两次,使用NSComparisonResult我可以得到正确的结果,直到晚上10点到11点59分。这两次的结果正好相反。有人知道这有什么问题吗?下面是示例代码和场景。晚上10:30:00是测试的时间,但您可以在任何时间进行测试 // For test, Current time 10:30:00 PM let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyl

我需要在Swift中比较两次,使用NSComparisonResult我可以得到正确的结果,直到晚上10点到11点59分。这两次的结果正好相反。有人知道这有什么问题吗?下面是示例代码和场景。晚上10:30:00是测试的时间,但您可以在任何时间进行测试

// For test, Current time 10:30:00 PM
let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .LongStyle)

let closeTimeCompareResult: NSComparisonResult = currentTime.compare("10:00:00 PM EDT")
print("DinnerClose: \(closeTimeCompareResult.rawValue)")
// Expected result is -1 but, getting as 1

// It works perfect until 9:59:59 PM
let closeTimeCompareResult9: NSComparisonResult = currentTime.compare("9:00:00 PM EDT")
print("DinnerClose: \(closeTimeCompareResult9.rawValue)")
// As expected result is -1 

您正在执行字符串比较。所以您要比较这两个字符串,例如:

10:00:00 PM EDT
9:00:00 PM EDT
字符串比较从每个字符串的第一个字符开始,比较每个字符串的对应字符。
“东部夏令时10:00:00 PM”
的第一个字符是
“1”
“东部夏令时9:00:00 PM”
的第一个字符是
“9”
。在Unicode和ASCII中,
“9”是代码点57,
“1”是代码点49。自57>49以来,
“9”>“1”
,以及
“美国东部时间晚上9:00:00”>“美国东部时间晚上10:00”

您可能希望从输入日期中提取小时、分钟和秒,然后进行数字比较。如果您已经使用Swift 2.2升级到Xcode 7.3,那么您可以使用如下的:

let date = NSDate()
let components = NSCalendar.currentCalendar().components([.Hour, .Minute, .Second], fromDate: date)
let hms = (components.hour, components.minute, components.second)
if hms >= (21, 0, 0) && hms < (22, 30, 0) {
    print("\(date) is between 9 PM and 10:30 PM in the system's time zone.")
}
let date=NSDate()
让components=NSCalendar.currentCalendar().components([.Hour、.Minute、.Second],fromDate:date)
设hms=(components.hour、components.minute、components.second)
如果hms>=(21,0,0)和&hms<(22,30,0){
打印(“\(日期)在系统时区的晚上9点到晚上10:30之间。”)
}

您正在执行字符串比较。所以您要比较这两个字符串,例如:

10:00:00 PM EDT
9:00:00 PM EDT
字符串比较从每个字符串的第一个字符开始,比较每个字符串的对应字符。
“东部夏令时10:00:00 PM”
的第一个字符是
“1”
“东部夏令时9:00:00 PM”
的第一个字符是
“9”
。在Unicode和ASCII中,
“9”是代码点57,
“1”是代码点49。自57>49以来,
“9”>“1”
,以及
“美国东部时间晚上9:00:00”>“美国东部时间晚上10:00”

您可能希望从输入日期中提取小时、分钟和秒,然后进行数字比较。如果您已经使用Swift 2.2升级到Xcode 7.3,那么您可以使用如下的:

let date = NSDate()
let components = NSCalendar.currentCalendar().components([.Hour, .Minute, .Second], fromDate: date)
let hms = (components.hour, components.minute, components.second)
if hms >= (21, 0, 0) && hms < (22, 30, 0) {
    print("\(date) is between 9 PM and 10:30 PM in the system's time zone.")
}
let date=NSDate()
让components=NSCalendar.currentCalendar().components([.Hour、.Minute、.Second],fromDate:date)
设hms=(components.hour、components.minute、components.second)
如果hms>=(21,0,0)和&hms<(22,30,0){
打印(“\(日期)在系统时区的晚上9点到晚上10:30之间。”)
}

您比较字符串而不是日期…您比较字符串而不是日期…谢谢,是的,我在比较字符串。让我试试这个方法。谢谢,是的,我在比较字符串。让我试试这种方法。