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)
}
}
Hi @Breezy to make it work you need only to change a little thing
change the value of to parameter for start like this:
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:
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.And you don't need the
start
variable.