Search code examples
iosswiftnsdate

How to determine if a business is open given the hours of operation (Swift-iOS)


I have an app that I'm building in Swift that needs to determine if a store/restaurant is currently open. It queries a database that I have control of, so I can set the open hours however I'd like. Currently I have an openTime/closeTime column for each day of the week set as a timestamp. For example: MonOpen = 11:00, MonClose = 19:00.

How can I use swift to determine if the place of business is currently open? I'm imagining something like if currentTime > MonOpen & currentTime < MonClose {...

An example of this is the iOS Starbucks app. If you go to locations, each location is listed with an "Open until 22:00" or "Open until 23:00."


Solution

  • It's just a matter of playing with the timezone, whether you use the user system's timezone or let them choose another one in the app's settings:

    let tz = NSTimeZone.defaultTimeZone()
    let now = NSCalendar.currentCalendar().componentsInTimeZone(tz, fromDate: NSDate())
    
    if now.weekDay == 2 && now.hour > MonOpen && now.hour < MonClose {
        // The store is open
    }