Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert Date to required format

I need to convert 2022-01-20T00:00:00.000Z to "dd MMM yyy" format.
I have tried doing it as suggested in a stackoverflow answer but it returns nil

func convertDate(date:String)-> String{
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat =  "yyyy-MM-dd'T'HH:mm:ssZ"
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "dd MMM yyy"
    if let date = dateFormatterGet.date(from: String(date)) {
       let convertedDate = dateFormatterPrint.string(from: date)
       return convertedDate
    } else {
       print("There was an error decoding the string")
    }
   return "nil"
}

Please help me ,thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The fractional seconds are missing in the date format string. It’s yyyy-MM-dd'T'HH:mm:ss.SSSZ.

And you are not using the date parameter. To avoid confusion with the local variable date rename it.

And you don’t need two date formatters and it’s highly recommended to set the Locale to a fixed value

func convertDate(dateString: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

    if let date = dateFormatter.date(from: dateString) {
       dateFormatter.dateFormat = "dd MMM yyy"
       return dateFormatter.string(from: date)
    } else {
       print("There was an error decoding the string")
       return ""
    }
   
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading