gpt4 book ai didi

ios - 创建时间间隔 Swift 列表

转载 作者:可可西里 更新时间:2023-11-01 00:23:28 24 4
gpt4 key购买 nike

您好,我无法创建从一个时间开始直到到达另一个时间的固定时间间隔列表。你能帮助我吗? ( swift 2.0)

例子:

我有两次 (8:00 - 23:00)。我知道间隔的持续时间(30 分钟)。作用域是创建一个时间间隔数组(8:00-8:30、8:30 - 9:00 等)。我使用对象调用 Time(start:Int, end:Int)

谢谢

最佳答案

您可以创建一个这样的类来生成那样的间隔,

struct Time {

let start: TimeInterval
let end: TimeInterval
let interval: TimeInterval

init(start: TimeInterval, interval: TimeInterval, end: TimeInterval) {
self.start = start
self.interval = interval
self.end = end
}

init(startHour: TimeInterval, intervalMinutes: TimeInterval, endHour: TimeInterval) {
self.start = startHour * 60 * 60
self.end = endHour * 60 * 60
self.interval = intervalMinutes * 60
}

var timeRepresentations: [String] {
let dateComponentFormatter = DateComponentsFormatter()
dateComponentFormatter.unitsStyle = .positional
dateComponentFormatter.allowedUnits = [.minute, .hour]

var dateComponent = DateComponents()
return timeIntervals.map { timeInterval in
dateComponent.second = Int(timeInterval)
return dateComponentFormatter.string(from: dateComponent)!
}
}

var timeIntervals: [TimeInterval]{
return Array(stride(from: start, through: end, by: interval))
}
}

然后您可以生成时间表示数组,

let time = Time(startHour: 8, intervalMinutes: 30, endHour: 23)

print(time.timeRepresentations)

然后生成,

["8:00", "8:30", "9:00", "9:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00"]

要检索范围,请将此代码放在末尾

let time = Time(startHour: 9, intervalMinutes: 30, endHour: 17)

let ranges = time.timeRepresentations.enumerated().compactMap { index, value -> String? in
if index + 1 < time.timeRepresentations.count {
return value + " - " + time.timeRepresentations[index + 1]
}
return nil
}

print(ranges.joined(separator: "\n"))

结果是,

9:00 - 9:30
9:30 - 10:00
10:00 - 10:30
10:30 - 11:00
11:00 - 11:30
11:30 - 12:00
12:00 - 12:30
12:30 - 13:00
13:00 - 13:30
13:30 - 14:00
14:00 - 14:30
14:30 - 15:00
15:00 - 15:30
15:30 - 16:00
16:00 - 16:30
16:30 - 17:00

关于ios - 创建时间间隔 Swift 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33210059/

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