Swift - Convert date and time object from server to local time on iphone

若如初见. 提交于 2019-12-13 02:25:18

问题


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
}

How can I convert this object to the local date and time of the iPhone in swift?

Thank you.


回答1:


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)!

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.


来源:https://stackoverflow.com/questions/37668553/swift-convert-date-and-time-object-from-server-to-local-time-on-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!