4

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?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Related: [Swift: Print all dates between two NSDate()](https://stackoverflow.com/questions/32536612/swift-print-all-dates-between-two-nsdate). – Martin R Mar 20 '18 at 14:59

1 Answers1

28

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]
*/
Ahmad F
  • 30,560
  • 17
  • 97
  • 143