This question already has answers here:
Using DateFormatter on a Unix timestamp
(5个答案)
去年关门了。
这是sysDictionary
"sys":{"type":1,"id":3721,"message":0.0038,"country":"CA","sunrise":1521544743,"sunset":1521588663}

if let sysDictionary = jsonObj!.value(forKey: "sys") as? NSDictionary {
   if let sunrise = sysDictionary.value(forKey: "sunrise"){

     DispatchQueue.main.async {
        self.sunriseLabel.text = "Sunrise: (sunrise)"

// this code is displaying the sunrise 1521544743 into my app not hrs/mins/sec format,

最佳答案

日出和日落时间看起来像unix时间戳。您可以从中创建一个Date对象,以便在应用程序中使用initialiserDate(timeIntervalSince1970: sunrise)
为了在用户界面中实际显示此日期,您需要使用一个DateFormatter,它接受一个Date,并输出一个人类可读的字符串,准备放入您的标签中。
下面是一个如何实现这一点的例子。

if let jsonObj = jsonObj as? [String: Any],
    let sysDictionary = jsonObj["sys"] as? [String: Any],
    let sunrise = sysDictionary["sunrise"] as? NSNumber {

    let sunriseDate = Date(timeIntervalSince1970: sunrise.doubleValue)
    let formatter = DateFormatter()
    formatter.dateStyle = .none
    formatter.timeStyle = .medium

    let formattedTime = formatter.string(from: sunriseDate)
    print(formattedTime)
    DispatchQueue.main.async {
        self.sunriseLabel.text = "Sunrise: \(formattedTime)"
    }
}

// prints "12:19:03 AM" using your example JSON

要转换JSON中的速度,有两种选择,第一种是自己完成:
let ms: Double = 1
let kmh = ms * 60 * 60 / 1000
print(kmh)
// prints 3.6

或者您可以使用Foundation为您进行转换,并清楚地说明您在做什么(IMO是推荐的方法):
var measurement = Measurement(value: 1, unit: UnitSpeed.metersPerSecond)
measurement.convert(to: .kilometersPerHour)
print(measurement.value)
// prints 3.5999971200023

let speedFormatter = MeasurementFormatter()
speedFormatter.unitOptions = .providedUnit
speedFormatter.unitStyle = .medium
let formattedSpeed = speedFormatter.string(from: measurement)
print(formattedSpeed)
// prints "3.6 kph"

07-24 09:45
查看更多