Swift-在iPhone上将日期和时间对象从服务器转换为本地时间 [英] Swift - Convert date and time object from server to local time on iphone
本文介绍了Swift-在iPhone上将日期和时间对象从服务器转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用php(laravel)向我的数据库发出请求,该请求返回一个日期对象,如下所示:
I make a request to my database with php (laravel) which return a date object as follow:
"lastMessageDate" : {
"date" : "2016-06-06 23:37:32.000000",
"timezone" : "UTC",
"timezone_type" : 3
}
如何快速将此对象转换为iPhone的本地日期和时间?
How can I convert this object to the local date and time of the iPhone in swift?
谢谢。
推荐答案
import Foundation
let serverDateFormatter: NSDateFormatter = {
let result = NSDateFormatter()
result.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSS"
result.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return result
}()
let s = "2016-06-06 23:37:32.000000"
let d = serverDateFormatter.dateFromString(s)!
上面的代码将产生一个NSDate对象。日期对象知道如何处理时区。因此,例如,如果您想向用户显示日期,则可以使用为本地时区设置的日期格式程序:
The above will produce an NSDate object. Date objects know how to deal with time zones. So if, for example you want to display the date to a user you can use a date formatter set for the local time zone:
let localDateFormatter: NSDateFormatter = {
let result = NSDateFormatter()
result.dateStyle = .MediumStyle
result.timeStyle = .MediumStyle
return result
}()
print(localDateFormatter.stringFromDate(d)) // prints "Jun 6, 2016, 7:37:32 PM" in my time zone.
这篇关于Swift-在iPhone上将日期和时间对象从服务器转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文