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

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

    The Following soltion get current time from the system and then check it exist that range or not . In my case time range is 8:00 am to 5:00 pm The Solution Valid for Swift 4.2

     func CheckTime()->Bool{
        var timeExist:Bool
        let calendar = Calendar.current
        let startTimeComponent = DateComponents(calendar: calendar, hour:8)
        let endTimeComponent   = DateComponents(calendar: calendar, hour: 17, minute: 00)
    
        let now = Date()
        let startOfToday = calendar.startOfDay(for: now)
        let startTime    = calendar.date(byAdding: startTimeComponent, to: startOfToday)!
        let endTime      = calendar.date(byAdding: endTimeComponent, to: startOfToday)!
    
        if startTime <= now && now <= endTime {
            print("between 8 AM and 5:30 PM")
            timeExist = true
        } else {
            print("not between 8 AM and 5:30 PM")
            timeExist = false
        }
        return timeExist
    }
    

提交回复
热议问题