Syed e Hussaini Syed e Hussaini - 1 month ago 16
Swift Question

Convert UTC NSDate into Local NSDate not working

I have a string getting from server as

"yyyy-MM-dd'T'HH:mm:ss.SSS'Z"

I convert this string into NSDate by this formate.

class func convertUTCDateToLocateDate(dateStr:String) -> NSDate{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(dateStr)


dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(date!)
let dateForm = NSDateFormatter()
dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateForm.timeZone = NSTimeZone.localTimeZone()
let dateObj = dateForm.dateFromString(timeStamp)
return dateObj!
}


Suppose the parameter string is "2016-11-05T12:00:00.000Z" but when i convert this string and return a
NSDate
object it doesn't change the time according to my local time. I get my correct time in the
timeStamp
string (in above code). But when i try to convert that
timeStamp
string into NSDate it again shows that date and time which i got as a parameter.

Answer

You shouldnt change a NSDate's time. NSDates are just a point in time, counted by seconds. They have no clue about timezones, days, month, years, hours, minutes, seconds,… If printed directly they will always output the time in UTC.
If you change the date to show you the time of your timezone you are actually altering the time in UTC — hence your date becomes representing another point in time, no matter of the timezone.
Keep them intact by not altering them, instead when you need to display them do it via a date formatter.
If you need to do time calculations that are independent of timezones you also can work with NSDateComponents instead.