我想知道在您看来哪个是快速比较没有特定日期的两个不同时间的最佳方式
目前我一直在考虑以这种方式实现
static func isClosingTime() -> Bool {
let currentHour = Calendar.current.component(.hour, from: Date())
let currentMinute = Calendar.current.component(.minute, from: Date())
currentHour >= 19 && currentMinute <= 30
}
我想知道是否有更好的方法
我接受所有关于干净正确代码的建议
从你的解释看来你
希望 isClosingTime 函数在当前时间大于 19:30 时返回“True”值
基于此,我可以建议这样做:
Date
对象像这样:
func isClosingTime(hour: Int, minute: Int) -> Bool {
guard let closingTime = Calendar.current.date(bySettingHour: hour, minute: minute, second: 0, of: Date()) else {
return false // could not establish closing time
}
return Date() >= closingTime
}
你称之为
isClosingTime(hour: 19, minute; 30)
我还将更新您需要处理关闭 _and_opening 时间的情况的答案。
func shouldBeOpen(from opening: (Int, Int), to closing: (Int, Int)) -> Bool {
guard let openingTime = Calendar.current.date(bySettingHour: opening.0, minute: opening.1, second: 0, of: Date()),
let closingTime = Calendar.current.date(bySettingHour: closing.0, minute: closing.1, second: 0, of: Date()) else {
return false // could not establish closing time
}
return (openingTime ... closingTime).contains(Date())
}
例如:
shouldBeOpen(from: (9, 0), to: (19, 30))
这里唯一的限制是它工作1天,并且关闭时间应该>开放时间。但即使这样也可以处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句