SwiftStarter SwiftStarter - 26 days ago 9
Swift Question

Swift 3 function to print out last 7 days in formatted string

I got a code snippet from one of the other threads, but I was wondering if someone could help me convert this function so that it prints out the day in this format: "dd-MM-yyyy". At the moment it's only printing the day.

func getLast7Dates()
{
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)
}


I know I will need to use:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd-MM-yyyy"


But I don't know where to put it in the function as this is my first time working with dates.

Thanks for your help :)

Answer

Setup the formatter once in your function and use it as follows (not lots of other small changes):

func getLast7Dates()
{
    let cal = Calendar.current
    let date = cal.startOfDay(for: Date())
    var days = [String]()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"    

    for i in 1 ... 7 {
        let newdate = cal.date(byAdding: .day, value: -i, to: date)!
        let str = dateFormatter.string(from: newdate)
        days.append(str)
    }

    print(days)
}