gpt4 book ai didi

swift - 如何以给定的粒度生成两个日期之间的每个日期?

转载 作者:行者123 更新时间:2023-11-28 11:39:01 24 4
gpt4 key购买 nike

如何以给定的粒度生成两个日期之间的每个日期?

我想让这个扩展板成为一个日期数组,所有日期都必须在 00 米、15 米、30 米或 45 米处,这样就没有间隙。 (可选)设置开始日期和结束日期,它们不在原始集合中(因此您可以有前导日期和尾随日期)。

extension TimeSeries {
var earliest: Date? {
return timeSeries.map { $0.date }.min()
}
var latest: Date? {
return timeSeries.map { $0.date }.max()

}
func pad (to repletion: Int, _ component: Calendar.Component, from: Date? = nil, to: Date? = nil) {
guard let start = from ?? self.earliest else {
print("no start date given and none available")
return
}
guard let end = to ?? self.latest else {
print("no end date given and none available")
return
}

// magic happens here...
}
}

具体来说,给定:

[ Date/* 2018-01-16 01:15:00 */, Date/* 2018-01-16 01:45:00 */]

我希望数组变成:

[ Date/* 2018-01-16 01:15:00 */,  Date/* 2018-01-16 01:30:00 */, Date/* 2018-01-16 01:45:00 */]

如果它像 ts.pad(to: 15, .minutes, from: Date/* 2018-01-16 01:00:00 */, to: Date/* 2018-01- 16 02:00:00 */)

我希望数组变成:

[ Date/* 2018-01-16 01:00:00 */, Date/* 2018-01-16 01:15:00 */,  Date/* 2018-01-16 01:30:00 */, Date/* 2018-01-16 01:45:00 */, Date/* 2018-01-16 02:00:00 */]

最佳答案

逻辑可能是这样的。创建以开始日期作为第一个元素的数组。然后将添加组件的日期附加到最后一个日期,直到新日期应该大于结束日期

func pad(to repletion: Int, _ component: Calendar.Component, from: Date? = nil, to: Date? = nil) {

guard let start = from ?? self.earliest, let end = to ?? self.latest else {
print("no date given and none available")
return
}

var components = DateComponents()
components.setValue(repletion, for: component)
let calendar = Calendar.current

var dates = [start] // results

while start < end {
if let newDate = calendar.date(byAdding: components, to: dates.last!),
newDate <= end {
dates.append(newDate)
} else { break }
}

}

关于swift - 如何以给定的粒度生成两个日期之间的每个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225487/

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