时间之间的快速比较



我有当前时间,我需要检查当前时间是否在两次之间。

但我遇到了麻烦,因为你可以看到startDateendDate打印过去的日期。

你能帮我一把吗?

func getDate() -> Bool {
let start = "07:00"
let end = "19:00"
let dateFormat = "HH:mm"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let startDate = dateFormatter.date(from: start)
let endDate = dateFormatter.date(from: end)
let currentDate = Date()
guard let startDate = startDate, let endDate = endDate else {
fatalError("Date Format does not match ⚠️")
}

print(startDate < currentDate && currentDate < endDate)
print(startDate) //2000-01-01 06:00:00 +0000
print(endDate) //2000-01-01 22:59:00 +0000
print(currentDate) //2021-07-13 22:11:05 +0000
return startDate < currentDate && currentDate < endDate
}

您只需要将DateFormatter defaultDate设置为当前日期的开始。如果你想让它也能在午夜(24:00(工作,你只需要将日期格式化程序isLenient设置为true。请注意,如果您在方法中创建日期格式化程序,则每次调用此方法时都会创建一个新的日期格式化程序:


extension Formatter {
static let time: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = .init(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm"
formatter.defaultDate = Calendar.current.startOfDay(for: Date())
formatter.isLenient = true
return formatter
}()
}

func isTimeBetween(start: String, end: String) -> Bool {
Formatter.time.defaultDate = Calendar.current.startOfDay(for: Date())
guard
let start = Formatter.time.date(from: start),
let end = Formatter.time.date(from: end) else {
print("invalid time input")
return false
}
print(start.description(with: .current))  // Tuesday, July 13, 2021 at 11:00:00 PM
print(end.description(with: .current))    // Wednesday, July 14, 2021 at 12:00:00 AM
print(Date().description(with: .current)) // Tuesday, July 13, 2021 at 11:42:02 PM 
return start...end ~= Date()
}

isTimeBetween(start: "23:00", end: "24:00")  // true

这将打印:

2021年7月13日星期二晚上11:00:00巴西利亚标准时间
2021年7月14日星期三上午12:00:00巴西里亚标准时间

您可以使用Calendar.current.date(bySetting...)设置现有日期的小时/秒/分钟。然后,比较这些结果。

func getDate() -> Bool {
let currentDate = Date()

let startDate = Calendar.current.date(bySettingHour: 7, minute: 0, second: 0, of: currentDate)
let endDate = Calendar.current.date(bySettingHour: 19, minute: 0, second: 0, of: currentDate)
guard let startDate = startDate, let endDate = endDate else {
fatalError("Date creation failed ⚠️")
}

print(startDate < currentDate && currentDate < endDate)
print(startDate)
print(endDate)
print(currentDate)
return startDate < currentDate && currentDate < endDate
}

相关内容

  • 没有找到相关文章

最新更新