两个日期之间的快速分钟间隔

时间:2021-06-07 16:46:31

标签: ios swift

我想返回一个日期数组,其中每个日期都是 startDate 和 endDate 之间的 15 分钟间隔

即:startDate 时间为 2pm,endDate 时间为 3pm,所需结果将是一个包含以下日期格式的数组 [2:15pm, 2:30pm, 2:45pm]

我收集了一些框架代码,但还没有达到我想要的结果。

private func getTimeIntervals(startTime: Date, endTime: Date) -> [Date] {
        let timeIntervals = []
        //get both times sinces refrenced date and divide by 60 to get minutes
        let startTimeMinutes = startTime.timeIntervalSinceReferenceDate/60
        let endTimeMinutes = endTime.timeIntervalSinceReferenceDate/60
        
        while(startTimeMinutes < endTimeMinutes) {
            // Add each 15 minute Date time interval into the timeIntervalsArray
        }

        return timeIntervals
    }

任何帮助将不胜感激,提前致谢。

1 个答案:

答案 0 :(得分:3)

使用日历功能date(byAdding:value:to:wrappingComponents:)

func dates(fromStart start: Date,
           toEnd end: Date,
           component: Calendar.Component,
           value: Int) -> [Date] {
    var result = [Date]()
    var working = start
    repeat {
        result.append(working)
        guard let new = Calendar.current.date(byAdding: component, value: value, to: working) else { return result }
        working = new
    } while working <= end
    return result
}

这是一个正常运行的操场中的代码:

import UIKit

func dates(fromStart start: Date,
           toEnd end: Date,
           component: Calendar.Component,
           value: Int) -> [Date] {
    var result = [Date]()
    var working = start
    repeat {
        result.append(working)
        guard let new = Calendar.current.date(byAdding: component, value: value, to: working) else { return result }
        working = new
    } while working <= end
    return result
}

extension Date {
    var localDate: String {return DateFormatter.localizedString(from: self, dateStyle: .medium, timeStyle: .medium)}
}

let threePMComponents = DateComponents(year: 2021, month: 6, day: 7, hour: 15)
guard let threePM = Calendar.current.date(from: threePMComponents) else {
    fatalError()
}

let sixPMComponents = DateComponents(year: 2021, month: 6, day: 7, hour: 18)
guard let sixPM = Calendar.current.date(from: sixPMComponents) else {
    fatalError()
}

print("Start time = \(threePM.localDate)")
print("End time = \(sixPM.localDate)")


let datesInRange = dates(fromStart: threePM, toEnd: sixPM, component: .minute, value: 15)
for item in datesInRange {
    print(item.localDate)
}

输出为:

Start time = Jun 7, 2021 at 3:00:00 PM
End time = Jun 7, 2021 at 6:00:00 PM
Jun 7, 2021 at 3:00:00 PM
Jun 7, 2021 at 3:15:00 PM
Jun 7, 2021 at 3:30:00 PM
Jun 7, 2021 at 3:45:00 PM
Jun 7, 2021 at 4:00:00 PM
Jun 7, 2021 at 4:15:00 PM
Jun 7, 2021 at 4:30:00 PM
Jun 7, 2021 at 4:45:00 PM
Jun 7, 2021 at 5:00:00 PM
Jun 7, 2021 at 5:15:00 PM
Jun 7, 2021 at 5:30:00 PM
Jun 7, 2021 at 5:45:00 PM
Jun 7, 2021 at 6:00:00 PM

如果您希望函数“捕捉”到指定日历组件的下一个偶数间隔,它会更复杂。