简体   繁体   English

如何从Twitter API解析月份和年份返回JSON

[英]How to Parse Month and Year from Twitter API returned JSON

Suppose Twitter returns Wed Sep 14 18:52:57 +0000 2011 in JSON format. 假设Twitter以JSON格式返回Wed Sep 14 18:52:57 +0000 2011 How do i go about parsing it so that the display looks something like Sep 2011 . 我如何解析它,使显示看起来像Sep 2011 Im aware of DateFormatter . 我知道DateFormatter I tried the following code but it keeps returning me Null . 我尝试了以下代码,但它一直让我回归Null

NSString *created = [(NSDictionary *)TWData objectForKey:@"created_at"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM yyyy"];
    NSDate *date = [dateFormatter dateFromString:created];
   tweetingSince.text= [NSString stringWithFormat:@"@%@",[dateFormatter    stringFromDate:date]];

You are using same date format to parse the input string created to NSDate and to create final output format from the parsed date. 您使用相同的日期格式来解析为NSDate created的输入字符串,并从解析的日期创建最终输出格式。 Date formatter is unable to parse date Wed Sep 14 18:52:57 +0000 2011 using date format MMM yyyy . 日期格式化程序无法使用日期格式MMM yyyy解析日期Wed Sep 14 18:52:57 +0000 2011 This is why the date is nil. 这就是date为零的原因。

Edit: Also quick googling gave me this result on SO: iPhone + Twitter API: Converting time? 编辑:也快速谷歌搜索给了我这个结果在SO: iPhone + Twitter API:转换时间?

Edit 2: Your code with proper NSDate parsing would look like this 编辑2:使用正确的NSDate解析的代码看起来像这样

NSString *created = [(NSDictionary *)TWData objectForKey:@"created_at"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
//  Parse input string to NSDate
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:created];
//  Convert parsed date to output format
[dateFormatter setDateFormat:@"MMM yyyy"];
tweetingSince.text= [NSString stringWithFormat:@"@%@",[dateFormatter    stringFromDate:date]];

You can do it like this 你可以这样做

NSString *myString = @"Wed Sep 14 18:52:57 +0000 2011";

    NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@" "];
    NSArray *components = [myString componentsSeparatedByCharactersInSet:delimiters];

    NSLog(@"dilip-%@",components);

Output will be 输出将是

dilip-(
    Wed,
    Sep,
    14,
    "18:52:57",
    "+0000",
    2011
)

Now you can select any value from array and create new string using that value. 现在,您可以从数组中选择任何值,并使用该值创建新字符串。

NSString * firstStr = [components objectAtIndex:1];
NSString * secondStr = [components objectAtIndex:5];


NSString * fullStr = [NSString stringWithFormat:@"%@ %@",firstStr,secondStr];

NSLog(@"dilip - %@",fullStr);

Output will be 输出将是

dilip - Sep 2011

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM