mohamede1945
mohamede1945

Reputation: 7198

NSDate to String with TimeZone Offset

I've the following code

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)

dateFormatter.stringFromDate(NSDate())

It produces date in the following format: 2015-08-06T15:44:49+0000 But I want it to be in the following format 2015-08-06T15:44:49+00:00

As you can see the offset needs to b +00:00 instead of +0000

Upvotes: 3

Views: 1092

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236295

You need to use "xxx" instead of "Z".

edit/update Swift 3 or later:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxx"
dateFormatter.string(from: Date())  // "2019-03-22T14:36:07+00:00"

If you need some reference you can use this:

enter image description here

Upvotes: 7

Related Questions