Search code examples
iosswiftxcodensdateformatter

How to convert String to Date to String in Swift?


I have this type of string, "2019-03-22", and want to convert it to this string, "March 22, 2019", in Swift.

It looks simple and I tried a few different ways. But I haven't figured it out yet.

The best code I have is this:

let originalDate = "2019-03-22"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let newDate = dateFormatter.string(from:originalDate)!
print(newDate)

But I get this error Cannot convert value of type 'String' to expected argument type 'Date'

How do I fix this?


Solution

  • You are trying to convert string(from: string which is not possible.

    You have first to convert the string to date with the format yyyy-MM-dd and then change the format and convert it back to string.

    let dateString = "2019-03-22"
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let date = dateFormatter.date(from: dateString)!
    dateFormatter.dateFormat = "MMMM dd, yyyy"
    let newDate = dateFormatter.string(from:date)
    print(newDate)