Search code examples
iosswiftstringnsdatensdateformatter

How to convert date of string format to another string format in swift(ios)


I have a string "2020-01-01T00:00:00". How shall I convert it to another string of format "01-Jan-2020" in swift (iOS)?

The conversion is from String to String.


Solution

  • let inputDate = "2020-01-01T00:00:00"
    
    let dateFmt = DateFormatter()
    dateFmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    
    if let date = dateFmt.date(from: inputDate) {
        dateFmt.dateFormat = "dd-MMM-yyyy"
        print(dateFmt.string(from: date))
    }