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
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
}