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

前端 未结 11 1212
一整个雨季
一整个雨季 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 04:01

    extension Date { 
        /// time returns a double for which the integer represents the hours from 1 to 24 and the decimal value represents the minutes.  
        var time: Double {
            Double(Calendar.current.component(.hour, from: self)) + Double(Calendar.current.component(.minute, from: self)) / 100
        }
    }
    
    // usage 
    print(9.30...16.30 ~= Date().time ? "If you're on the East Coast, It is during market hours" : "its after hours")
    

提交回复
热议问题