-3

I have a "createdAt" date string that I want to format like EEEE, MMM d, yyyy in Swift 4.

var createdAt:String = ""

And a function that formats a date

func getFormattedDate(date: Date, format: String) -> String {
    let dateformat = DateFormatter()
    dateformat.dateFormat = format
    return dateformat.string(from: date)
}

I can use this function to correctly format todays date like so:

let formatingDate = getFormattedDate(date: Date(), format: "EEEE, MMM d, yyyy")
Text(formatingDate)

But how do I make it so it correctly formats my "createdAt" string not just todays date?

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
Tom Wicks
  • 785
  • 2
  • 11
  • 28

1 Answers1

0

You need

func getFormattedDate(str:String, format: String) -> String { 
    let dateformat = DateFormatter()
    dateformat.locale = Locale(identifier: "en_US_POSIX") 
    dateformat.dateFormat = "createAtForm"
    let dInpu = dateformat.date(from: str)!
    dateformat.dateFormat = format
    return dateformat.string(from:dInpu)
}

let formatingStr = getFormattedDate(str: createdAt, format: "EEEE, MMM d, yyyy") 
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87