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

时间:2019-01-16 21:15:58

标签: swift

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

我想将此扩展板制成一系列日期,所有日期都必须在00m,15m,30m或45m处,以便没有间隙。 (可选)设置开始日期和结束日期(不在原始集中)(这样您就可以拥有开始日期和结束日期)。

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 */]

2 个答案:

答案 0 :(得分:1)

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

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 }
    }

}

答案 1 :(得分:1)

这是我的变体,假设期限由startend个日期给出

let quarter: TimeInterval = 15 * 60
let dateInterval = DateInterval(start: start, end: end)

var date = start
var result = [Date]()
while dateInterval.contains(date) {
    result.append(date)
    date = date.addingTimeInterval(quarter)
}