sbkl sbkl - 9 months ago 49
Swift Question

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

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.

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.