问题
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
回答1:
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.
回答2:
The date format has to be assigned to the dateFormat property of the date formatter instead.
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 then you would add for example
Swift 3.*
dateFormatter.timeZone = NSTimeZone(name: "UTC")
Swift 4.*
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
also refer link http://www.brianjcoleman.com/tutorial-nsdate-in-swift/
回答3:
Swift 4.0
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
来源:https://stackoverflow.com/questions/32046550/nsdate-set-timezone-in-swift