Consider that we have a function signature as:
func datesRange(from: Date, to: Date) -> [Date]
which should take from
date and to
date instances and returns an array containing the dates (days) between its parameters. How to achieve it?
Consider that we have a function signature as:
func datesRange(from: Date, to: Date) -> [Date]
which should take from
date and to
date instances and returns an array containing the dates (days) between its parameters. How to achieve it?
You could implement it like this:
func datesRange(from: Date, to: Date) -> [Date] {
// in case of the "from" date is more than "to" date,
// it should returns an empty array:
if from > to { return [Date]() }
var tempDate = from
var array = [tempDate]
while tempDate < to {
tempDate = Calendar.current.date(byAdding: .day, value: 1, to: tempDate)!
array.append(tempDate)
}
return array
}
Usage:
let today = Date()
let nextFiveDays = Calendar.current.date(byAdding: .day, value: 5, to: today)!
let myRange = datesRange(from: today, to: nextFiveDays)
print(myRange)
/*
[2018-03-20 14:46:03 +0000,
2018-03-21 14:46:03 +0000,
2018-03-22 14:46:03 +0000,
2018-03-23 14:46:03 +0000,
2018-03-24 14:46:03 +0000,
2018-03-25 14:46:03 +0000]
*/