SwiftStarter
SwiftStarter

Reputation: 247

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 :)

Upvotes: 0

Views: 631

Answers (3)

C1FR1
C1FR1

Reputation: 133

you will want to use this:

print(dateFormatter.stringFromDate(date))

the documentation for this is here

Upvotes: 0

rmaddy
rmaddy

Reputation: 318794

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)
}

Upvotes: 2

Alexander
Alexander

Reputation: 63167

instead of appending the day to the array, append the date. Then, return the array of dates, and map over them with your date formatter:

import Foundation

func getLast7Dates() -> [Date] {
    let today = Date()

    var days = [Date]()

    for i in 1 ... 7 {
        let date = Calendar.current.date(byAdding: .day, value: -i, to: today)!
        days.append(date)
    }

    return days
}

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"

let dateStrings = getLast7Dates().map(dateFormatter.string(from:))

print(dateStrings)

You can make it even shorter:

func getLast7Dates() -> [Date] {
    let today = Date()

    return (-7 ... -1).map{ Calendar.current.date(byAdding: .day, value: $0, to: today)!
    }
}

Upvotes: 0

Related Questions