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

前端 未结 11 1214
一整个雨季
一整个雨季 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:50

    In Swift 3.0 you can use the new Date value type and compare directly with ==,>,< etc

        let now = NSDate()
        let nowDateValue = now as Date
        let todayAtSevenAM = calendar.date(bySettingHour: 7, minute: 0, second: 0, of: nowDateValue, options: [])
        let todayAtTenPM = calendar.date(bySettingHour: 22, minute: 0, second: 0, of: nowDateValue, options: [])
    
        if nowDateValue >= todayAtSevenAM! &&
            nowDateValue <= todayAtTenPM!
        {
            // date is in range
    
        }
    

    Very handy indeed.

提交回复
热议问题