我不确定x-www-form-urlencoded,因为我对其进行了测试,如果我将日期发送为0,它会将其解码为2001-01-01 00:00:00 +0000,我认为它肯定应该是1970-01-01 00:00:00 +0000。
但使用 JSON 有效负载,您可以灵活地根据需要提供 JSONDecoder。
struct Payload: Content {
var date: Date
}
如果您想将日期作为 UNIX 时间戳发送
router.post("check") { req throws -> Future<String> in
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970 // choose it for unix-timestamp
return try req.content.decode(json: Payload.self, using: decoder).map { p in
return String(describing: p.date)
}
}
如果您想以自己的格式发送日期
router.post("check") { req throws -> Future<String> in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter) // custom date formatter
return try req.content.decode(json: Payload.self, using: decoder).map { p in
return String(describing: p.date)
}
}
因此,对于 unix-timestamp,您应该发送 1970 年的秒数,例如0 将被解码为1970-01-01 00:00:00 +0000。
对于上述自定义格式,您应该发送2018-01-01 00:00:00 之类的日期以将其解码为2018-01-01 00:00:00 +0000
UPD:你可以写一个扩展来漂亮地解码
extension ContentContainer where M: Request {
func decodeJson<D>(_ payload: D.Type) throws -> Future<D> where D: Decodable {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
return try decode(json: payload, using: decoder)
}
}
那么你就可以像这样解码你的有效载荷
router.post("check") { (req) throws -> Future<String> in
return try req.content.decodeJson(Payload.self).map { p in
return String(describing: p.date)
}
}