how to check if time is within a specific range in swift

前端 未结 11 1250
一整个雨季
一整个雨季 2020-12-05 03:24

Hi I am trying to check if the current time is within a time range, say 8:00 - 16:30. My code below shows that I can obtain the current time as a string, but I am unsure how

11条回答
  •  星月不相逢
    2020-12-05 03:55

    You can use the compare method from NSDate: it will return an NSComparisonResult (OrderedSame, OrderedAscending or OrderedDescending) that you can check against your start and end dates:

    let dateMaker = NSDateFormatter()
    dateMaker.dateFormat = "yyyy/MM/dd HH:mm:ss"
    let start = dateMaker.dateFromString("2015/04/15 08:00:00")!
    let end = dateMaker.dateFromString("2015/04/15 16:30:00")!
    
    func isBetweenMyTwoDates(date: NSDate) -> Bool {
        if start.compare(date) == .OrderedAscending && end.compare(date) == .OrderedDescending {
            return true
        }
        return false
    }
    
    println(isBetweenMyTwoDates(dateMaker.dateFromString("2015/04/15 12:42:00")!)) // prints true
    println(isBetweenMyTwoDates(dateMaker.dateFromString("2015/04/15 17:00:00")!)) // prints false
    

提交回复
热议问题