Reputation: 227
Suppose Twitter returns Wed Sep 14 18:52:57 +0000 2011
in JSON format. How do i go about parsing it so that the display looks something like Sep 2011
.
Im aware of DateFormatter
. I tried the following code but it keeps returning me 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]];
Upvotes: 0
Views: 135
Reputation: 7704
You are using same date format to parse the input string created
to NSDate
and to create final output format from the parsed date. Date formatter is unable to parse date Wed Sep 14 18:52:57 +0000 2011
using date format MMM yyyy
. This is why the date
is nil.
Edit: Also quick googling gave me this result on SO: iPhone + Twitter API: Converting time?
Edit 2: Your code with proper NSDate
parsing would look like this
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]];
Upvotes: 1
Reputation: 9143
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
Upvotes: 1