UNIX Timestamp out of JSON String

Hi,

I am trying to convert a Unix Timestamp inside my Codable struct but it decodes it a little bit wrong.
Do you have a suggestion for me ?

UNIX String: 1680291600
Right Date: Fri Mar 31 2023 19:40:00 GMT+0000
My Result wrong result: 20/01/70 11:44:51

I think I need a ISO8601DateFormatter() but how can I run it ?

struct Times: Codable {
let schedOut: String

enum CodingKeys: String, CodingKey {
    case schedOut = "sched_out"
}

/*
let dateFormatter : DateFormatter = {
     let formatter = DateFormatter()
     formatter.dateFormat = "dd/MM/yy HH:mm:ss"
     return formatter
 }()

 var dateString : String {
     let timeInterval = TimeInterval(schedOut)!
     let date = Date(timeIntervalSince1970: timeInterval / 1000)
     return dateFormatter.string(from:date)
 }

Close! What you need to do is tell your JSONDecoder to use: .secondsSince1970. Basically tell the decoder, how to decode the date. The formatters are only used in views (how you want to format / represent the date), like how you showed “Fri Mar 31 2023 19:40:00 GMT+0000”

The decoder decodes the integer into a date object, and then you can represent that day in whatever format you want, using DateFormatter

struct Times: Codable {
    let schedOut: Date
    enum CodingKeys: String, CodingKey {
        case schedOut = "sched_out"
    }
}

// Making an example JSON data
let json = """
{
    "sched_out": 1680291600
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970

do {
    let object = try decoder.decode(Times.self, from: json)
    print(object) // this prints: Times(schedOut: 2023-03-31 19:40:00 +0000)
} catch {
    print("error: \(error)")
}
1 Like