如何根据营业时间 (Swift-iOS) 确定企业是否营业

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

我有一个正在 Swift 中构建的应用程序,它需要确定 store/restaurant 当前是否打开。它查询我可以控制的数据库,因此我可以根据需要设置开放时间。目前,我将一周中的每一天设置为 openTime/closeTime 列作为时间戳。例如:MonOpen = 11:00, MonClose = 19:00.

如何使用 swift 确定营业地点当前是否营业?我在想象 if currentTime > MonOpen & currentTime < MonClose {...

这方面的一个例子是 iOS 星巴克应用程序。如果您前往地点,每个地点都会列出 "Open until 22:00" 或 "Open until 23:00."

这只是玩弄时区的问题,无论您使用用户系统的时区还是让他们在应用程序设置中选择另一个时区:

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
}

我想再回答一下这个问题,因为我们现在有 Swift 5.1,而且大多数企业的营业时间比小时更复杂。

import Foundation

// There might be an enum in Swift 
// that I did not bother to lookup
enum Days : Int {
    case Sun = 1
    case Mon = 2
    case Tue = 3
    case Wed = 4
    case Thu = 5
    case Fri = 6
    case Sat = 7
}

func isOfficeOpenNow(weekSchedule: [Days: (Int, Int)]) -> Bool {
    let tz = NSTimeZone.default
    let now = NSCalendar.current.dateComponents(in: tz, from: Date())

    guard let weekday = now.weekday,
        let today = Days(rawValue: weekday),
        let hour = now.hour,
        let minute = now.minute else {
            return false
    }

    guard let todayTuple = weekSchedule[today] else {
        return false // no key, means closed
    }

    let opensAt = todayTuple.0
    let closesAt = todayTuple.1

    assert(opensAt < closesAt, "Your schedule is setup wrong.")

    let rightNowInMinutes = hour * 60 + minute

    return rightNowInMinutes > opensAt &&
        rightNowInMinutes < closesAt
}

要使用它,只需为每一天定义一个字典。

关键是星期几。可以使用字符串 "Mon"、"Tue" 等 但是你需要一个映射或 DateFormatter

值是一个元组 (int, int) for (open, close) 以分钟为单位 使用分钟,因为许多商店有更复杂的开放 关闭时间不只是小时

let schedule = [
    Days.Mon: (9*60+30, 22*60+30),
    Days.Tue: (9*60+30, 23*60+05),
    Days.Wed: (9*60+30, 22*60+30),
    Days.Thu: (9*60+30, 22*60+30),
    Days.Fri: (9*60+30, 22*60+30),
]


if isOfficeOpenNow(weekSchedule: schedule) {
    print("Store open")
} else {
    print("Store closed")
}

如果特定的一周是假期,只需更新该周的日程安排,一切都会好起来的。

如果某天休息,只需从日程表中删除钥匙即可。