adrian Coye
adrian Coye

Reputation: 173

use NSDateFormatter to parse Twitter strings

I'm trying to create a NSDate from a string returned by the twitter API As I spent hours on this issue I created a sample app

NSString *testDate = @"Mon Jul 25 21:20:58 +0000 2011";
NSDateFormatter *frm = [[NSDateFormatter alloc] init];
[frm setDateStyle:NSDateFormatterLongStyle];
[frm setFormatterBehavior:NSDateFormatterBehavior10_4];
[frm setDateFormat: @"EEE MMM dd HH:mm:ss 'Z' yyyy"];
NSDate *newDate = [frm dateFromString:testDate];
NSLog(@"newDate:%@", newDate);

To me this code 'should' work.

all I got is this :

2011-07-25 19:36:08.467 test[92:707] Test
2011-07-25 19:36:08.475 test[92:707] newDate:(null)

I found this but it's not working either.

I have Lion + Xcode 4.1 My iPad is under 4.3.5

Thanks in advance for any help ;)

Upvotes: 3

Views: 914

Answers (3)

wjl
wjl

Reputation: 7361

For anyone finding this via Google, Twitter has apparently changed their date formats, at least for their http://search.twitter.com/search.json endpoint.

NSDate __attribute__((pure)) *parseTwitterDate(NSString *twitterDate) {
    NSDateFormatter *twitterDateFormatter = NSDateFormatter.new;
    [twitterDateFormatter setDateFormat: @"EEE, dd MMM yyyy HH:mm:ss Z"];
    return [twitterDateFormatter dateFromString:twitterDate];
};

Upvotes: 1

adrian Coye
adrian Coye

Reputation: 173

Here is what worked for me

no quotes around Z like said Dave DeLong. I used setLocale on the NSDateFormatter, it made it work better.

NSDateFormatter *frm = [[NSDateFormatter alloc] init];
[frm setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[frm setDateFormat:@"EEE MMM dd HH:mm:ss Z yyyy"];

Upvotes: 3

Dave DeLong
Dave DeLong

Reputation: 243156

Don't kick yourself too hard...

In your format string, remove the apostrophes from around Z. The apostrophes mean that it's going to be a literal Z, not the timezone. If you remove those, it'll work correctly.

Upvotes: 5

Related Questions