A method which returns an array of dates that are

2019-07-22 14:12发布

问题:

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)
            }
        }

回答1:

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.



回答2:

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)
            }
        }