Search code examples
swiftdatensdateformatterdate-formattingswift5

I am new to dateformatters, picked date and time from datepicker and need to converted to required from before sending to the server


picked date and time from datepicker and need to converted to required from before sending to the server. not able to convert to the required from.

func convertToUTC(dateToConvert:String) -> String {
      let formatter = DateFormatter()
      formatter.dateFormat = "EEE MMM d yyyy HH:mm:ss.SSS'Z"

      let convertedDate = formatter.date(from: dateToConvert)
      formatter.timeZone = TimeZone(identifier: "UTC")
      return formatter.string(from: convertedDate!)
         }

requred date form is Sat Aug 1 2020 23:38:56 GMT+0530

Solution

  • You can simply create two date formats, one to parse the input date string and another to convert the date to your server date format:

    extension Formatter {
        static let inputDate: DateFormatter = {
            let dateFormatter = DateFormatter()
            dateFormatter.locale = .init(identifier: "en_US_POSIX")
            dateFormatter.dateFormat = "EEE MMM d yyyy HH:mm:ss.SSSZ"
            return dateFormatter
        }()
        static let serverDate: DateFormatter = {
            let dateFormatter = DateFormatter()
            dateFormatter.locale = .init(identifier: "en_US_POSIX")
            dateFormatter.dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'xxxx"
            return dateFormatter
        }()
    }
    

    func convertToServer(input: String) -> String? {
        guard let date = Formatter.inputDate.date(from: input) else { return nil }
        return Formatter.serverDate.string(from: date)
    }
    
    convertToServer(input: "Sat Aug 1 2020 23:38:56.123Z") // "Sat Aug 1 2020 20:38:56 GMT-0300"