Title says it all. I don't mind getting the date as "598146673" but I just need to convert it when I receive that on my Django. Ideally, I would like to what format it is or how I can have xcode leave it in "2019-12-15 23:51:13 +0000"
Asked
Active
Viewed 130 times
0
-
Your date value it is the time interval the date and the reference date `January 1st 2001 at UTC` `Date(timeIntervalSinceReferenceDate: 598146673) // "Dec 15, 2019 at 8:51 PM"` – Leo Dabus Dec 03 '19 at 22:35
-
If you are decoding it using JSONDecoder that's the default date decoding strategy `.deferredToDate` – Leo Dabus Dec 03 '19 at 22:43
1 Answers
2
You can use a custom encoding to send the date to your Django service as a formatted string, like this:
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"}"

Mike Taverne
- 9,156
- 2
- 42
- 58