Swift将unix时间转换为日期和时间 [英] Swift convert unix time to date and time
本文介绍了Swift将unix时间转换为日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前的代码:
if let var timeResult = (jsonResult["dt"] as? Double) {
timeResult = NSDate().timeIntervalSince1970
println(timeResult)
println(NSDate())
}
结果:
println(timeResult)
= 1415639000.67457
println(timeResult)
= 1415639000.67457
println(NSDate())
= 2014-11-10 17:03:20 +0000只是为了测试看看 NSDate
提供了什么。
println(NSDate())
= 2014-11-10 17:03:20 +0000 was just to test to see what NSDate
was providing.
我希望第一个看起来像最后一个。 dt的值= 1415637900。
I want the first to look like the last. The value for dt = 1415637900.
此外,我如何调整时区?在 iOS 上运行。
Also, how can I adjust to time zone? Running on iOS.
推荐答案
要将日期显示为当前时区,我使用的是以下。
To get the date to show as the current time zone I used the following.
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)
self.defaults.setObject(localDate, forKey: "localdate")
}
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)
}
这篇关于Swift将unix时间转换为日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文