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?
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 v10.12 (Sierra).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With