Reputation: 24
I have a Json Data which contains 2 Key:Value "startDate":"2008.11",
and "endDate":"2011.10",
respectively, and what i wanna do is to loop through the date range until this statement becomes false:
while startDate <= endDate {
let range += startDate + 1
print(range)
}
something similar like this.. .
how to loop through the date range in swift?
Upvotes: 0
Views: 1296
Reputation: 52118
Assuming you have extracted the json values you can use DateComponents to calculate the number of months between the values
let startDate = "2008.11".split(separator: ".").compactMap {Int($0)}
let endDate = "2011.10".split(separator: ".").compactMap {Int($0)}
//Maybe add a check here that both arrays are of length 2
let startComponents = DateComponents(year: startDate[0], month: startDate[1])
let endComponents = DateComponents(year: endDate[0], month: endDate[1])
let months = Calendar.current.dateComponents([.month], from: startComponents, to: endComponents).month!
And now you can use a simple for loop
for n in 0..<months {
//...
}
If you want to work with days (and dates) you can calculate them as
let days = Calendar.current.dateComponents([.day], from: startComponents, to: endComponents).day!
but you need to decide what day in month to use for startDate
and endDate
Upvotes: 1