在 Swift 中比较没有日期的两次时间的最佳方法是什么
What is the best way to compare two times without a date in Swift
我想知道在 swift
中,您认为哪个是比较没有特定日期的两个不同时间的最佳方式
目前我一直在想这样实现
static func isClosingTime() -> Bool {
let currentHour = Calendar.current.component(.hour, from: Date())
let currentMinute = Calendar.current.component(.minute, from: Date())
currentHour >= 19 && currentMinute <= 30
}
我想知道有没有更好的方法
我接受所有关于干净和正确代码的建议
从你的解释看来是你
want the isClosingTime function to return a "True" value when the current time is greater than 19:30
基于此,我可以建议这样做:
- 获取关闭时间作为
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天,关闭时间应该>打开时间。但即使这样也可以处理。
我想知道在 swift
中,您认为哪个是比较没有特定日期的两个不同时间的最佳方式目前我一直在想这样实现
static func isClosingTime() -> Bool {
let currentHour = Calendar.current.component(.hour, from: Date())
let currentMinute = Calendar.current.component(.minute, from: Date())
currentHour >= 19 && currentMinute <= 30
}
我想知道有没有更好的方法
我接受所有关于干净和正确代码的建议
从你的解释看来是你
want the isClosingTime function to return a "True" value when the current time is greater than 19:30
基于此,我可以建议这样做:
- 获取关闭时间作为
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天,关闭时间应该>打开时间。但即使这样也可以处理。