Skip to content

Instantly share code, notes, and snippets.

@liuzhida33
Created October 30, 2020 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuzhida33/ce754a0c54e56b56879f9dbb05f35817 to your computer and use it in GitHub Desktop.
Save liuzhida33/ce754a0c54e56b56879f9dbb05f35817 to your computer and use it in GitHub Desktop.
private struct OrderTime: Sequence, IteratorProtocol {
struct DayHour {
let date: Date
let hours: [Date]
}
let minimumDate: Date
let maximumDate: Date
init(minimumDate: Date, maximumDate: Date) {
self.minimumDate = minimumDate
self.maximumDate = maximumDate
}
var underestimatedCount: Int {
if let workOffDate = Date(hour: 17, minute: 0, second: 0, nanosecond: 0),
let endDate = Date()?.end(of: .day),
minimumDate > workOffDate, minimumDate < endDate {
/// offset date 在当天下班时间之后
return Swift.max(0, maximumDate.daysSince(minimumDate).int - 1)
} else {
return Swift.max(0, maximumDate.daysSince(minimumDate).int)
}
}
private var offsetDay = 0
private var offsetDate = Date()
mutating func next() -> DayHour? {
defer {
offsetDay += 1
}
offsetDate = minimumDate.adding(.day, value: offsetDay)
guard offsetDate < maximumDate else {
return nil
}
if let workOnDate = Date(hour: 8, minute: 0, second: 0, nanosecond: 0),
let workOffDate = Date(hour: 17, minute: 0, second: 0, nanosecond: 0),
offsetDate > workOnDate, offsetDate < workOffDate {
/// offset date 在当天工作时间内
let hours = (Swift.max(workOnDate.hour, offsetDate.hour)...Swift.min(workOffDate.hour, offsetDate.hour))
.compactMap({ Date(year: offsetDate.year, month: offsetDate.month, day: offsetDate.day, hour: $0, minute: 0, second: 0, nanosecond: 0) })
return hours.isEmpty ? nil : DayHour(date: offsetDate, hours: hours)
} else if let workOffDate = Date(hour: 17, minute: 0, second: 0, nanosecond: 0),
let endDate = Date()?.end(of: .day),
offsetDate > workOffDate, offsetDate < endDate {
/// offset date 在当天下班时间之后
return nil
} else {
let hours = (8...17).compactMap({ Date(year: offsetDate.year, month: offsetDate.month, day: offsetDate.day, hour: $0, minute: 0, second: 0, nanosecond: 0) })
return hours.isEmpty ? nil : DayHour(date: offsetDate, hours: hours)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment