1

I'm trying to get an array of dates between the time stamp of one of my objects and 30 days into the future.

I've used the code below but i'm not getting the desired result and am having trouble trying to make a method described in the title. Any help would be great, thank you.

var dates = [Date]()
    func fetchDays() {
            let cal = Calendar.current

            var dateComponents = DateComponents()
            dateComponents.year = 2017
            dateComponents.month = 2
            dateComponents.day = 12

            guard let startDate = cal.date(from: dateComponents) else {
                return }

            var start = cal.startOfDay(for: startDate)

            for _ in 0 ... 30 {
    guard let daysBetween = cal.date(byAdding: .day, value: 1, to: startDate) else { return }
                start = daysBetween
                dates.append(start)
            }
        }
rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

2

You are adding 1 to the same start date so your array is filled with the same date over and over. Simply replace 1 with the loop index + 1.

for i in 0 ... 30 {
    if let newDate = cal.date(byAdding: .day, value: i + 1, to: startDate) {
        dates.append(newDate)
    }
}

And you don't need the start variable.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

Hi @Breezy to make it work you need only to change a little thing

change the value of to parameter for start like this:

  for _ in 0 ... 30 {
    guard let daysBetween = cal.date(byAdding: .day, value: 1, to: start) else { return }
                start = daysBetween
                dates.append(start)
            }

Edited:

if you don't want to use 30 days you can add a month end then get the days between the 2 dates like this:

var dates = [Date]()
        func fetchDays() {
            let cal = Calendar.current

            var dateComponents = DateComponents()
            dateComponents.year = 2017
            dateComponents.month = 2
            dateComponents.day = 12

            guard let startDate = cal.date(from: dateComponents) else {
                return }

            var start = cal.startOfDay(for: startDate)
            guard let endDate = cal.date(byAdding: .month, value: 1, to: start) else { return }

            guard let daysBetween = cal.dateComponents([.day], from: start, to: endDate).day else { return }

            for _ in 0 ... daysBetween {
                guard let newDate = cal.date(byAdding: .day, value: 1, to: start) else { return }
                start = newDate
                dates.append(newDate)
            }
        }
José Neto
  • 530
  • 2
  • 10
  • later in the project the length of how many days i'll need might change from a month to maybe even 100 days, which is why i thought it would be best to use two dates instead. But thanks! This really helped a lot. –  Feb 27 '17 at 17:13