gpt4 book ai didi

swift - 在 Swift 2 中实现时间框架的方法

转载 作者:搜寻专家 更新时间:2023-10-31 19:38:28 27 4
gpt4 key购买 nike

这是食堂营业时间

Monday - Thursday: 10:30 am - 12:00 am
Friday: 10:30 am - 9:00 pm
Saturday - Sunday: Closed

我正在实现一个函数,该函数根据当前时间返回该地点是否开放或关闭的状态。有没有一种更简单、更有效的方法来实现这样的事情而不用处理复杂的“if”语句?

func displayStatusForBrandywine () -> String
{
let currentDateTime = NSDate()
// get the user's calendar
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Year,
NSCalendarUnit.Month,
NSCalendarUnit.Day,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Weekday
]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: currentDateTime)
var status: String = ""

if ((dateTimeComponents.weekday >= 2 && dateTimeComponents.weekday <= 5) && (dateTimeComponents.hour >= 10 && dateTimeComponents.hour <= 23) && (dateTimeComponents.minute <= 59 && dateTimeComponents.hour != 0) || ((dateTimeComponents.weekday == 6 && dateTimeComponents.hour >= 10 && dateTimeComponents.minute >= 30 && dateTimeComponents.hour <= 21) || (dateTimeComponents.weekday == 6 && dateTimeComponents.hour >= 11 && (dateTimeComponents.hour <= 21 && dateTimeComponents.minute < 0))))
{
status = "Open"
}
else
{
status = "Closed"
}
return status
}

最佳答案

这是一个有趣的方法...

struct OpenPeriod {
var day: Int
var openTime: Double
var closeTime: Double

func isOpen(dateTime: NSDate) -> Bool {
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Weekday
]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: dateTime)
if dateTimeComponents.weekday != self.day { return false }
let timeOfDay = Double(dateTimeComponents.hour) + Double(dateTimeComponents.minute) / 60
return timeOfDay >= self.openTime && timeOfDay <= self.closeTime
}
}

var openingTimes = [OpenPeriod]()
openingTimes.append(OpenPeriod(day: 2, openTime: 10.5, closeTime: 12))
openingTimes.append(OpenPeriod(day: 3, openTime: 10.5, closeTime: 12))
openingTimes.append(OpenPeriod(day: 4, openTime: 10.5, closeTime: 12))
openingTimes.append(OpenPeriod(day: 5, openTime: 10.5, closeTime: 21))

func open(dateTime: NSDate) -> Bool {
return openingTimes.reduce(true, combine: { $0 && $1.isOpen(dateTime) })
}

open(NSDate()) ? "Open" : "Closed"

关于swift - 在 Swift 2 中实现时间框架的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34435782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com