John Deere John Deere - 5 months ago 20
JSON Question

Get NSDate from JSON?

I am working with Openweather API and trying to parse date property from JSON. This is date format: "dt" - Time of data calculation, unix, UTC. I have Forecast struct and there i've

var date: NSDate
. In
weatherManager.swift
i am working with SwiftyJSON and i tried with
let date = json["dt"].double
and other extension but it won't work.

Any suggestion? Thanks

Answer

If the date inside the API response is Unix timestamp, that means that you have to convert it to NSDate object. Since the unix time timestamp is number of seconds (in OpenWeather API) elapsed from 1. January 1970, we can use NSDate(timeIntervalSince1970:) method to convert it to NSDate object that you need.

let dateUnix = json["dt"].double
let date = NSDate(timeIntervalSince1970: dateUnix)

date object is now NSDate that you need.

Comments