Search code examples
swiftnsdate

NSDate set timezone in swift


how can i return a NSDate in a predefined time zone from a string

let responseString = "2015-8-17 GMT+05:30"
var dFormatter = NSDateFormatter()
dFormatter.dateFormat = "yyyy-M-dd ZZZZ"
var serverTime = dFormatter.dateFromString(responseString)
println("NSDate : \(serverTime!)")

the above code returns the time as

2015-08-16 18:30:00 +0000

Solution

  • how can i return a NSDate in a predefined time zone?

    You can't.

    An instance of NSDate does not carry any information about timezone or calendar. It just simply identifies one point in universal time.

    You can interpret this NSDate object in whatever calendar you want. Swift's string interpolation (the last line of your example code) uses an NSDateFormatter that uses UTC (that's the "+0000" in the output).

    If you want the NSDate's value as a string in the current user's calendar you have to explicitly set up a date formatter for that.