【问题标题】:How to Parse Month and Year from Twitter API returned JSON如何从 Twitter API 返回 JSON 解析月份和年份
【发布时间】:2013-05-17 13:58:15
【问题描述】:

假设 Twitter 以 JSON 格式返回 Wed Sep 14 18:52:57 +0000 2011。我该如何解析它以使显示看起来像Sep 2011。 我知道DateFormatter。我尝试了以下代码,但它一直返回给我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]];

【问题讨论】:

  • 如果你总是有相同的字符串格式而不是仅仅分解字符串并从你的字符串中获取你想要显示的值
  • 您的意思是通过NSMakeRange 或其他方式从字符串中选择子字符串。我不太确定,但我不相信 Twitter 会很快改变格式。值得一试!!
  • 是的,你可以这样做,检查我的答案。

标签: iphone json twitter nsdateformatter


【解决方案1】:

您正在使用相同的日期格式将输入字符串 created 解析为 NSDate,并根据解析的日期创建最终输出格式。日期格式化程序无法使用日期格式 MMM yyyy 解析日期 Wed Sep 14 18:52:57 +0000 2011。这就是date 为零的原因。

编辑: 快速谷歌搜索也给了我这个结果:iPhone + Twitter API: Converting time?

编辑 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]];

【讨论】:

  • 嗯,你说得对,卢卡斯!!愚蠢的我..虽然我不知道该怎么做
  • 我想知道为什么谷歌从来没有为我抛出好的搜索:D!尝试并测试了这个..它就像一个魅力!谢谢老哥!!
  • 谢谢迪利普。我喜欢你回答它的优雅和简单,它肯定会满足 holier 的需求 ;-) NSDate 在应用程序本地化时非常有用
【解决方案2】:

你可以这样做

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

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

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

输出将是

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

现在您可以从数组中选择任何值并使用该值创建新字符串。

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


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

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

输出将是

dilip - Sep 2011

【讨论】:

  • 很抱歉把你的绿色勾去掉了!!!我相信下面提到的更适合我的编码风格!但是如果有人在读这个:这个答案是完全合法的!
  • 没问题。好的答案必须得到赞赏,卢卡斯给出了很好的答案。
  • 顺便说一句,您的解决方案可以使用NSArray *components = [myString componentsSeparatedByString:@" "] ;-)
猜你喜欢
  • 2021-01-30
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多