Bogdan Bogdanov Bogdan Bogdanov - 4 months ago 34
iOS Question

Swift - Get last 7 days starting from today in array

How to get previous 7 days of the month I know how to get if today is 18, but what if today id 3rd November? How to get the last 4 days from the previous month(October) in Int?

Answer

Use NSCalendar and NSDateComponents:

let cal = NSCalendar.currentCalendar()
// start with today
var date = cal.startOfDayForDate(NSDate())

var days = [Int]()

for i in 1 ... 7 {
    // get day component:
    let day = cal.component(.DayCalendarUnit, fromDate: date)
    days.append(day)

    // move back in time by one day:
    date = cal.dateByAddingUnit(.DayCalendarUnit, value: -1, toDate: date, options: nil)!
}

println(days)

Update for Swift 2.2 (Xcode 7.3.1):

let cal = NSCalendar.currentCalendar()
var date = cal.startOfDayForDate(NSDate())
var days = [Int]()
for i in 1 ... 7 {
    let day = cal.component(.Day, fromDate: date)
    days.append(day)
    date = cal.dateByAddingUnit(.Day, value: -1, toDate: date, options: [])!
}
print(days)

Update for Swift 3 (Xcode 8 beta 2):

let cal = Calendar.current
var date = cal.startOfDay(for: Date())
var days = [Int]()
for i in 1 ... 7 {
    let day = cal.component(.day, from: date)
    days.append(day)
    date = cal.date(byAdding: .day, value: -1, to: date)!
}
print(days)
Comments