我当前的代码:
if let var timeResult = (jsonResult["dt"] as? Double) { timeResult = NSDate().timeIntervalSince1970 println(timeResult) println(NSDate()) }
结果:
println(timeResult) = 1415639000.67457
println(timeResult)
println(NSDate())= 2014-11-10 17:03:20 +0000只是为了测试以查看NSDate提供了什么。
println(NSDate())
NSDate
我希望第一个看起来像最后一个。dt的值= 1415637900。
另外,如何调整时区?在 iOS上 运行。
为了使日期显示为当前时区,我使用了以下内容。
if let timeResult = (jsonResult["dt"] as? Double) { let date = NSDate(timeIntervalSince1970: timeResult) let dateFormatter = NSDateFormatter() dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style dateFormatter.timeZone = NSTimeZone() let localDate = dateFormatter.stringFromDate(date) }
Swift 3.0版本
if let timeResult = (jsonResult["dt"] as? Double) { let date = Date(timeIntervalSince1970: timeResult) let dateFormatter = DateFormatter() dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style dateFormatter.timeZone = self.timeZone let localDate = dateFormatter.string(from: date) }
斯威夫特5
if let timeResult = (jsonResult["dt"] as? Double) { let date = Date(timeIntervalSince1970: timeResult) let dateFormatter = DateFormatter() dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style dateFormatter.timeZone = .current let localDate = dateFormatter.string(from: date) }