I have allocated a date formatter, and I am trying to format a string which contains a date:
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *date = [[stories objectAtIndex:storyIndex] objectForKey:@"date"];
NSDate *formattedDate = [formatter dateFromString:date];
NSLog(@"%@", formattedDate);
As you can see I am 'NSLogging' the formattedDate to see if it had worked or not. Unfortunately it has not worked and therefore is returning 开发者_运维技巧(NULL).
Please could you tell me what I am doing wrong.
Thanks in advanced.
The string "Fri, 10 Dec 2010 23:48:36 +0000" is not a "short style".
To parse that reliably, set the locale and an explicit date format:
formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc]
initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[formatter setLocale:locale];
[formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSString *date = [[stories objectAtIndex:storyIndex] objectForKey:@"date"];
NSDate *formattedDate = [formatter dateFromString:date];
NSLog(@"%@", formattedDate);
Edit:
To then display the NSDate formattedDate in the format "Friday 10 December 2010", add this code after the above:
NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
[displayFormatter setLocale:locale];
[displayFormatter setDateFormat:@"EEEE dd MMMM yyyy"];
NSString *displayDate = [displayFormatter stringFromDate:formattedDate];
NSLog(@"displayDate = %@", displayDate);
[displayFormatter release];
For an explanation of the locale see Apple QA1480.
For an explanation of the date format see Unicode Date Format Patterns.
精彩评论