开发者

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 ap开发者_开发百科p

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 ;)


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.


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"];


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];
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜