Swift NSDate iso 8601 format

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?


You can use NSISO8601DateFormatter or ISO8601DateFormatter for Swift 3.0+

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

Need Your Help

Is it safe to kill a replicating MySQL-process which is 'copying to tmp table'?

mysql process replication

I'm having a problem on a master MySQL (5.0, Linux) server: I tried to add a comment to a table row, which translates into an ALTER TABLE command. Now the process is stuck on 'copy to tmp table', c...

Text inside element in desktop and outside in mobile

html css html5 css3

Good day I have been working in a responsive header which has a text inside an element but only in desktop screens, opening on mobile screens text should go after the element but with some formatting