If current time is between value 1 and value 2, run this code

How would I be able to make an if statement that could check the current time in the local time zone and see if it is between two set times.

For example, I want the if statment to be like "If the current time is between 13:00 and 15:00, run the code in the if statment".


How can I do this?

Accepted Reply

Did you write


if beginDate.date! < now {

}

Replies

You have to convert 13:00 and 15:00 of today to dates beginDate, endDate


then compare dates with now = Date()


if beginDate > now && now < endDate {

}

Yes, but how would I get the variables beginDate and endDate. Also it would need to work every day, not just a specified day.

Something like this


let now = Date()
let calendar = Calendar.current

let year = calendar.component(.year, from: now)
let month = calendar.component(.month, from: now)
let day = calendar.component(.day, from: now)
let beginDate = DateComponents(calendar: calendar, timeZone: .current, year: year, month: month, day: day, hour: 13, minute: 0)
let endDate = DateComponents(calendar: calendar, year: year, month: month, day: day, hour: 15, minute: 0)

Now I'm having a problem when making the if statment. It can't compare a type DateComponents (beginDate and endDate) to the type Date (now). I would assume you could add a .hour to all of them to make them, but that doesn't work.

Did you write


if beginDate.date! < now {

}

Thanks! That worked!