Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift NSDate ISO 8601 format

I am working on date formats in Swift and am trying to convert a string date to NSDate and an 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 the original string date. What is happening here?

like image 845
Mark Engl Avatar asked Feb 07 '23 01:02

Mark Engl


2 Answers

You can use NSISO8601DateFormatter or ISO8601DateFormatter for Swift 3.0+

like image 110
N. Krash Avatar answered Feb 13 '23 07:02

N. Krash


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 v10.12 (Sierra).

like image 44
Code Different Avatar answered Feb 13 '23 06:02

Code Different