Search code examples
iosswiftdatensdateformatterdate-formatting

String Date to Date in Swift


I am working with a backend that returns me a date string like 2020-05-05 10:19:25.357479+05:30. How can I convert this to a Date object in swift? According to the backend, the date format they use is YYYY-MM-DD HH:mm:ss.SSSSSS+|-hh:mm. But, when I try to use this string in the DateFormatter, I get an error that says - "Date string does not match format expected by formatter."

Can someone please help me with this?


Solution

  • You can use this Function

    func dateFromString(_ dateString:String,  format: String = "yyyy-MM-dd HH:mm:ss.SSSSSSZ") -> String? {
        let dateFormatter = DateFormatter()
        let tempLocale = dateFormatter.locale  // save locale temporarily
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat =  format//"yyyy-MM-dd HH:mm:ss.SSSSSS"
        let date = dateFormatter.date(from: dateString)
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
        dateFormatter.locale = tempLocale // reset the locale
    
        guard let getdate = date else {
          return nil
        }
    
        let dateString = dateFormatter.string(from: getdate)
        return dateString
      }
    

    how to use

    if let dateString = dateFromString("2020-05-05 10:19:25.357479+05:30") {
    
            print (dateString)
          }