I am getting from my server a string date in UTC time zone and I need to convert it to the local time zone.
MY CODE:
let utcTime = "2015-04-01T11:42:00.269Z"
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.dateFromString(utcTime)
println("utc: \(utcTime), date: \(date)")
this prints -
utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 11:42:00 +0000)
if I remove
dateFormatter.timeZone = NSTimeZone(name: "UTC")
it prints
utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 08:42:00 +0000)
my local time zone is UTC +3 and in the first option I get UTC in the second option I get UTC -3
I should get
utc: 2015-04-01T11:42:00.269Z, date: Optional(2015-04-01 14:42:00 +0000)
So how do I convert the UTC date format to local time?
Swift version of c_rath answer:
In Swift 3 this works well:
I had to remove both z and milli seconds from c_rath solution. Works in swift 4.
Try this Swift extension
Swift 4: UTC/GMT ⟺ Local (Current/System)
Expanding on what others have mentioned, here is a handy
NSDate
extension in SwiftSomething along the following worked for me in Objective-C :
I keep these two websites handy for converting different time formats: http://www.w3.org/TR/NOTE-datetime
http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/
In Swift it will be: