当我将 JSONEncoder 与 Date 类型一起使用时,我得到一个日期“598146673”
I am getting a date of "598146673" when I use JSONEncoder with a Date type
标题说明了一切。我不介意将日期设置为“598146673”,但我只需要在我的 Django 上收到它时将其转换。理想情况下,我想知道它是什么格式或如何让 xcode 将其保留在“2019-12-15 23:51:13 +0000”
您可以使用自定义编码将日期作为格式化字符串发送到您的 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"}"
标题说明了一切。我不介意将日期设置为“598146673”,但我只需要在我的 Django 上收到它时将其转换。理想情况下,我想知道它是什么格式或如何让 xcode 将其保留在“2019-12-15 23:51:13 +0000”
您可以使用自定义编码将日期作为格式化字符串发送到您的 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"}"