Prabhu Prabhu - 1 month ago 12
Swift Question

UTC to local time conversion not working in Swift 2

I am trying to convert a UTC time to local timezone, but it doesn't seem to be converting it at all:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = dateFormatter.dateFromString(dateStringFromServer)!
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let date2 = dateFormatter.dateFromString(dateStringFromServer)!


The
dateStringFromServer
is a string representation of a UTC date. So I was expecting date1 to be in UTC, and date2 to be in PDT (my local time zone), but they are both the same. Something wrong with my syntax?

This is what I'm getting:

dateStringFromServer: 2016-10-21T05:24:26.000Z
date1: 2016-10-21 05:24:26 +0000
date2: 2016-10-21 05:24:26 +0000


How can I get date2 be in the device's local timezone?

mat mat
Answer

If you want to convert to the time zone set on the device you can do this

Swift3

    let dateFormatter =  DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date1 = dateFormatter.date(from: dateStringFromServer)
    // return the timeZone of your device i.e. America/Los_angeles
    let timeZone = TimeZone.autoupdatingCurrent.identifier as String
    dateFormatter.timeZone = TimeZone(identifier: timeZone)
    let date2 = dateFormatter.string(from: date1)

Swift2

     let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date1 = dateFormatter.dateFromString(dateStringFromServer)
    // return the timeZone of your device i.e. America/Los_angeles
    let timeZone = NSTimeZone.localTimeZone().name
   dateFormatter.timeZone =  NSTimeZone(name: timeZone)
    let date2 = dateFormatter.stringFromDate(date1!)