I want to just be able to format my dates in the section titles of my table cleanly. Here’s my code:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *date = [dateFormatter dateFromString:sectionInfo.name];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(@"%@", formattedDate);
return formattedDate;
}
With this code, no section titles come up because date is null. For some reason dateFromString is not able to turn the string, sectionInfo.name into an NSDate. Any suggestions?
Taking into account your comment, where you point out that the format of your date title is 2012-03-12 07:00:00 +0000, you can be sure that the problem is in formatting.
NSDateFormatterMediumStyle has the format “Nov 23, 1937” – and this is your mismatch 🙂
You have to use something like:
to made an NSDate from the string of a format you have. Should work then.
If you need to return an NSString with NSDateFormatterMediumStyle format, then only after you got NSDate you can apply it to your dateFormatter object as you did:
and then use this dateFormatter to get the string from the date you got: