Answer the question
In order to leave comments, you need to log in
How to form an array with dates for a certain period of time in swift?
Greetings.
There is a task to generate an array with dates in the format 20150801, 20150802...
Let's put all the dates into the array starting from today and 3 months ago.
Tell me how to do it?
As far as I understand, you need to use NSCalendar?
Thank you.
Answer the question
In order to leave comments, you need to log in
You will need:
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
let gmtTimeZone = NSTimeZone(abbreviation: "GMT")
dateFormatter.timeZone = gmtTimeZone
dateFormatter.dateFormat = "yyyyMMdd"
var dates = [String]()
let threeMonthAgoComponent = NSDateComponents()
threeMonthAgoComponent.month = -3
var date = NSDate()
let calendar = NSCalendar.currentCalendar()
let lastDate = calendar.dateByAddingComponents(threeMonthAgoComponent, toDate: date, options: NSCalendarOptions(rawValue: 0))
let dayAgoComponent = NSDateComponents()
dayAgoComponent.day = -1
while (date != lastDate) {
date = calendar.dateByAddingComponents(dayAgoComponent, toDate: date, options: NSCalendarOptions.MatchFirst)!
dates.append(dateFormatter.stringFromDate(date))
}
print(dates)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question