问题
I am working on date formats in swift. Trying to covert string date to NSDate and NSSate to string date (ISO 8601 format)
This is my code
let stringDate = "2016-05-14T09:30:00.000Z" // iso 8601 format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" //iso 8601
let date = dateFormatter.dateFromString(stringDate)
print("Date = \(date)") // Output is 2016-05-14 16:30:00 +0000
// again converting it date to string using stringFromDate
print("\(dateFormatter.stringFromDate(date!))") // 2016-05-14T09:30:00.000Z
I am trying to understand why I am getting NSDate in GMT format (adding 7 hours to time 09:30 to 16:30 )?
If I convert that NSDate date
variable to string, then I am getting original string date. Can anyone help me to understand what is happening here?
回答1:
You can use NSISO8601DateFormatter or ISO8601DateFormatter for Swift 3.0+
回答2:
Your format string was wrong. You indicate a literal Z
instead of "Z as zulu time". Remove the single quotes:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
You should always specified the locale as en_US_POSIX
when parsing internet time. This is so commonly overlooked that Apple created the ISO8601DateFormatter
class in OS X 10.12
来源:https://stackoverflow.com/questions/39671011/swift-nsdate-iso-8601-format