Swift NSDate iso 8601 format

夙愿已清 提交于 2019-12-02 12:59:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!