M
M
MTemp2015-08-05 07:38:33
Calendar
MTemp, 2015-08-05 07:38:33

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

1 answer(s)
A
Alexander Tikhonov, 2015-08-05
@MTemp

You will need:

  • NSDateFormatter to set date format
  • NSDateComponents for adding/subtracting time units (days, months, years, etc.)
  • NSCalendar to specify the calendar type ( currentCalendar(), Gregorian or whatever)
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)

+ links
stackoverflow.com/how-do-i-add-1-day-to-a-nsdate
stackoverflow.com/nsdate-get-year-month-day

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question