I want to format a date from a string. I can do it this way:
NSString *str = @"Fri, 13 Jan 2012 12:25:49 +0000";
NSLog(@"String: %@", str);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"eee, dd MMM yyyy HH:mm:ss ZZZZ"];
NSDate *datefrom = [df dateFromString:str];
NSLog(@"NSDate: %@", datefrom);
[df setDateFormat:@"dd/MM/yyyy"];
str = [df stringFromDate:datefrom];
NSLog(@"Formated String: %@", str);
But that’s useless because I want to be able to format different dates. So when I do this:
NSString *str = [[stories objectAtIndex:0] objectForKey:@"date"];
NSLog(@"String: %@", str);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"eee, dd MMM yyyy HH:mm:ss ZZZZ"];
NSDate *datefrom = [df dateFromString:str];
NSLog(@"NSDate: %@", datefrom);
[df setDateFormat:@"dd/MM/yyyy"];
str = [df stringFromDate:datefrom];
NSLog(@"String Formatada: %@", str);
It simply doesn’t work. I checked the output for [[stories objectAtIndex:0] objectForKey:@”date”] and it’s exactly the same string as @”Fri, 13 Jan 2012 12:25:49 +0000″
I compared the 2 strings to check if I wasn’t reading them wrong. Here’s the code I used to compare:
if ([[[stories objectAtIndex:0] objectForKey:@"date"] isEqualToString:@"Fri, 13 Jan 2012 12:25:49 +0000"]) {
NSLog(@"They are the same");
}
else NSLog(@"They are NOT the same");
But they don’t seem to be the same because I always get “They are NOT the same” as the output, even though they’re visually exactly the same. Any idea?
Are you sure that the object returned by [[stories objectAtIndex:0] objectForKey:@”date”] is an NSString and not an NSDate object? It might look the same when you log it, so the only way to tell is to check the type which you could do by logging:
NSLog(@”%@”, NSStringFromClass([str class]));