0

标题说明了一切。我不介意将日期设为“598146673”,但当我在 Django 上收到它时,我只需要转换它。理想情况下,我想知道它是什么格式或如何让 xcode 将其保留在“2019-12-15 23:51:13 +0000”中

4

1 回答 1

1

您可以使用自定义编码将日期作为格式化字符串发送到您的 Django 服务,如下所示:

struct MyDjangoRequest: Encodable {

    let myDate: Date

    enum CodingKeys: String, CodingKey {
        case myDate = "myDate"
    }

    func encode(to encoder: Encoder) throws {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +0000"
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        let myFormattedDate = dateFormatter.string(from: myDate)

        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(myFormattedDate, forKey: .myDate)
    }
}

//encode your request
let r = MyDjangoRequest(myDate: Date())
let json = try? JSONEncoder().encode(r)

//have a look at it!
let s = String(data: json!, encoding: .utf8). 
//      "{"myDate":"2019-12-04 03:38:28 +0000"}"
于 2019-12-04T03:44:25.340 回答