代码之家  ›  专栏  ›  技术社区  ›  Pandurang Yachwad

NSComparisonResult在下午10点及以上时间未按预期工作

  •  0
  • Pandurang Yachwad  · 技术社区  · 9 年前

    我需要在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 
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   rob mayoff    9 年前

    您正在执行字符串比较。因此,您正在比较这两个字符串,例如:

    10:00:00 PM EDT
    9:00:00 PM EDT
    

    字符串比较从每个字符串的第一个字符开始,比较每个字符串的对应字符。的第一个字符 "10:00:00 PM EDT" "1" 和的第一个字符 "9:00:00 PM EDT" "9" 在Unicode和ASCII中, "9" 是代码点57 "1" 因为57>49, "9" > "1" "9:00:00 PM EDT" > "10:00:00 PM EDT" .

    您可能需要从输入日期中提取小时、分钟和秒,然后进行数字比较。如果您已使用Swift 2.2升级到Xcode 7.3,则可以使用 tuple comparison 这样地:

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