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
You can get year, month, and day from today's date, append those to those date time strings to build new Date
objects. Then compare
the todaysDate
to those two resulting Date
objects:
let todaysDate = Date()
let startString = "8:00"
let endString = "16:30"
// convert strings to `Date` objects
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let startTime = formatter.date(from: startString)
let endTime = formatter.date(from: endString)
// extract hour and minute from those `Date` objects
let calendar = Calendar.current
var startComponents = calendar.dateComponents([.hour, .minute], from: startTime!)
var endComponents = calendar.dateComponents([.hour, .minute], from: endTime!)
// extract day, month, and year from `todaysDate`
let nowComponents = calendar.dateComponents([.month, .day, .year], from: todaysDate)
// adjust the components to use the same date
startComponents.year = nowComponents.year
startComponents.month = nowComponents.month
startComponents.day = nowComponents.day
endComponents.year = nowComponents.year
endComponents.month = nowComponents.month
endComponents.day = nowComponents.day
// combine hour/min from date strings with day/month/year of `todaysDate`
guard
let startDate = calendar.date(from: startComponents),
let endDate = calendar.date(from: endComponents)
else {
print("unable to create dates")
return
}
// now we can see if today's date is inbetween these two resulting `NSDate` objects
let isInRange = todaysDate > startDate && todaysDate < endDate
See previous revision of this answer for Swift 2 answer.