Reputation: 2321
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.
Upvotes: 2
Views: 3494
Reputation: 33967
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.
Upvotes: 6