views:

397

answers:

2

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.

A: 

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.

Alan Rogers
+2  A: 

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.

David Gelhar
Thanks for pointing out the mismatch. I'm not sure how I can format the string to be like "2010-03-24T02:35:57Z"
Sheehan Alam
Similar question http://stackoverflow.com/questions/1263455/nil-nsdate-when-trying-to-get-date-from-utc-string-in-zulu-timeIn particular, note the suggestion that you may want to replace the final "Z" in the input string with an explicit numeric timezone (-0000)
David Gelhar
Thanks! In my case the date format should be yyyy-MM-dd'T'HH:mm:ssZ Replacing Z with (-0000) did the trick.
Sheehan Alam