0

I am trying to get a NSDate object from a UTC time string. The example of the time string is this:

2016-07-29T11:43:55+02:00

I am usingNSDateFormatter and set the formate as: yyyy-MM-dd'T'HH:mm:ss

However this gives me the take with incorrect time zone. So the above date will be: 2016-07-29T09:43:55+00:00

How do I keep the time zone aspect as well?

I did try adding a 'Z' to the end of the formatter but that just returns a nil date.

kb920
  • 3,039
  • 2
  • 33
  • 44
Robert J. Clegg
  • 7,231
  • 9
  • 47
  • 99
  • That's correct. 9 is two hours behind local time. – Robert J. Clegg Jul 29 '16 at 11:05
  • 1
    Possible duplicate of [Convert ISO 8601 to NSDate](http://stackoverflow.com/questions/17558859/convert-iso-8601-to-nsdate) – vadian Jul 29 '16 at 12:37
  • Your date format is correct and the date string is parsing correctly, so are you asking how you detect what GMT offset the incoming date string had? – Droppy Jul 29 '16 at 12:43

3 Answers3

2

Try this

 NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
 [userFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
 NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
 [userFormatter setLocale:posix];
 NSString *dateConverted = [userFormatter stringFromDate:theDate];
Bhushan Vaidya
  • 722
  • 1
  • 6
  • 17
0

Thanks to all that help. Solved the issue. The time on my iOS Simulator was correct. However when I called [NSDate date]; it show'd me a time two hours before local time. Hence the 'errors' I was seeing in the formatting of NSDate.

Robert J. Clegg
  • 7,231
  • 9
  • 47
  • 99
  • Showed you where? `NSLog()` by any chance? – Droppy Jul 29 '16 at 13:16
  • Yeah, NSLog. Is there a reason why the iOS Simulator shows correct time but NSLog doesn't? – Robert J. Clegg Jul 29 '16 at 13:17
  • Seriously; this is probably the single most asked questions on stackoverflow and I don't see any reason why an iOS/OSX developer wouldn't know about it. `NSLog()` calls `[NSDate description]` and `description` formats the date in UTC timezone. To show the date in a different time zone, set-up an `NSDateFormatter` (including the time zone) and use that to do date -> string conversion. – Droppy Jul 29 '16 at 13:19
  • Thanks for the explanation @Droppy – Robert J. Clegg Jul 29 '16 at 13:20
0

Use NSISO8601DateFormatter if targeting iOS 10 and above. https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

Ben Guild
  • 4,881
  • 7
  • 34
  • 60