Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 285
mohamede1945 Avatar asked Feb 16 '26 16:02

mohamede1945


1 Answers

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

like image 175
Leo Dabus Avatar answered Feb 18 '26 06:02

Leo Dabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!