我是 dateformatters 的新手,从 datepicker 中选择日期和时间,需要在发送到服务器之前转换为 required from

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

从日期选择器中选择了日期和时间,需要在发送到服务器之前转换为所需的日期和时间。 无法转换为所需的来源。

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

您可以简单地创建两种日期格式,一种用于解析输入日期字符串,另一种用于将日期转换为您的服务器日期格式:

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"