Sheehan Alam
Sheehan Alam

Reputation: 60879

How to convert a UTC date to NSDate?

I have a string that is UTC and would like to convert it to an NSDate.

static NSDateFormatter* _twitter_dateFormatter;
[_twitter_dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
[_twitter_dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
[_twitter_dateFormatter setLocale:_en_us_locale];

NSDate *d = [_twitter_dateFormatter dateFromString:sDate];

When I go through the debugger d is nil even though sDate is "2010-03-24T02:35:57Z"

Not exactly sure what I'm doing wrong.

Upvotes: 1

Views: 4003

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338634

Apple gives source code for Parsing an RFC 3339 date-time. If using ARC, you'll may want to adjust that source by removing the calls to 'autorelease'.

FYI, RFC 3339 is a subset of ISO 8601 with one deviation (negative zero offset is allowed in RFC 3339). So Apple’s code is killing two birds with one stone, handling the so-called 'Internet-style' RFC 3339 datetimes as well as simple datetimes of ISO 8601.

Upvotes: 0

David Gelhar
David Gelhar

Reputation: 27900

Ditto on the need to alloc/init your NSDateFormatter object, but you have another problem too: your Date format string does not match the actual date you're giving it.

"EEE MMM dd HH:mm:ss ZZZ yyyy"
- vs -
"2010-03-24T02:35:57Z"

That format string would match something like:

"Wed Mar 24 00:07:33 -0400 2010"

See the unicode standard for the meaning of the date format string.

Upvotes: 3

Alan Rogers
Alan Rogers

Reputation: 15058

You aren't allocating or initialising your NSDateFormatter object.

Try something like this:

NSDateFormatter* _twitter_dateFormatter = [[NSDateFormatter alloc] init];
[_twitter_dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
[_twitter_dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
[_twitter_dateFormatter setLocale:_en_us_locale];

NSDate *d = [_twitter_dateFormatter dateFromString:sDate];
[_twitter_dateFormatter release];

It's also unclear why you are declaring _twitter_dateFormatter as a static. If you are trying to avoid re-allocating it, make it an ivar of your class.

Upvotes: 1

Related Questions