Xernox Xernox - 2 years ago 202
Swift Question

Converting String to NSDate, wrong time zone

How to convert String to NSDate and then back to String?

I tried doing it like this:

//String to NSDate
let dateString = "2016-07-07T18:09:41Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(dateString)

//NSDate to String
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.locale = NSLocale(localeIdentifier: "en")
let time = formatter.stringFromDate(date!)

And time in my case is 21:09, even though it was 18:09. Setting locale does nothing. I guess I am doing something very wrong, just not sure what.

Answer Source

Locale doesn't set the time zone, it just helps set the format to that of the user's locale and preferences. Explicitly set the timeZone to get the results you want. For example, to set the time zone to the system time zone try:

dateFormatter.timeZone = NSTimeZone.systemTimeZone()

formatter.timeZone = NSTimeZone.systemTimeZone()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download