-1

Using alamofire İ am fetching JSON data in swift. Time value is integer and have iso8601 format. When İ am converting Unix datetime which in integer format from back end gives me weird value.

1570088096210 must have to convert to GMT: Thursday, October 3, 2019 7:34:56.210 AM but giving me 51724-02-10T10:16:00+00:00

Code:

 let dateValue = Double(AppData.time ?? 0)
 let dateFinal = Date(timeIntervalSince1970: dateValue).formattedISO8601
Newbie
  • 360
  • 3
  • 19

3 Answers3

1

Seems like you are getting milliseconds that you need to convert to seconds before creating date as,

let time: TimeInterval = 1570088096210/1000
let dateFinal = Date(timeIntervalSince1970: time)
print(dateFinal.description)

2019-10-03 07:34:56 +0000

Kamran
  • 14,987
  • 4
  • 33
  • 51
1

You are encouraged to use Decodable to parse the JSON. It can handle millisecondsSince1970 very smoothly including the conversion to Date

let json = """
{"date":1570088096210}
"""

struct PointInTime : Decodable {
    let date : Date
}

do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .millisecondsSince1970
    let result = try decoder.decode(PointInTime.self, from: Data(json.utf8))
    print(result.date) // 2019-10-03 07:34:56 +0000
} catch {
    print(error)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • cannot convert model structure data type. at back end it has integer data type. – Newbie Oct 03 '19 at 12:41
  • 1
    Look at the literal JSON. The date type **is** integer. And you can encode it back to integer with the same strategy. `Codable` is extremely flexible. – vadian Oct 03 '19 at 12:42
0

1570088096210 is actually 02/10/51724 @ 10:16pm (UTC)

Please, check your income data

Iliya Kisliy
  • 241
  • 1
  • 5