Use the Calendar function 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
}
Here is that code in a functioning playground:
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)
}
The output is:
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
If you want the function to "snap" to the next even interval of the specified calendar component it would be more involved.