NSDate sets the time zone to fast

how can I return NSDate to 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 
+10
source share
3 answers

How can I return NSDate to a predefined time zone?

You can not.

The NSDate instance NSDate not carry any time zone or calendar information. It just simply identifies one point in universal time.

You can interpret this NSDate in any calendar you want. String interpolation of strings (the last line of your NSDateFormatter code) uses NSDateFormatter , which uses UTC (which is "+0000" in the output).

If you want the NSDate value as a string in the current user calendar, you need to explicitly set the date format for this.

+11
source

Instead, the date format should be assigned to the dateFormat property of the date formatter.

 let date = NSDate.date() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let str = dateFormatter.stringFromDate(date) println(str) 

This prints the date using the default time zone on the device. only if you want the output according to a different time zone, add for example

Swift 3. *

 dateFormatter.timeZone = NSTimeZone(name: "UTC") 

Swift 4. *

 dateFormatter.timeZone = TimeZone(abbreviation: "UTC") 

also link to the link http://www.brianjcoleman.com/tutorial-nsdate-in-swift/

+38
source

Swift 4.0

 dateFormatter.timeZone = TimeZone(abbreviation: "UTC") 
+10
source

All Articles