我希望能够干净地格式化表格部分标题中的日期。这是我的代码:
- (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;
}
使用此代码,不会出现任何节标题,因为日期为空。由于某种原因 dateFromString 无法将字符串,sectionInfo.name 转换为 NSDate。有什么建议吗?
最佳答案
考虑到您的评论,您指出日期标题的格式是 2012-03-12 07:00:00 +0000,您可以确定问题出在格式上。
NSDateFormatterMediumStyle 的格式为“Nov 23, 1937” - 这是您的不匹配:)
你必须使用类似的东西:
[dateFormatter setDateStyle:@"yyyy-dd-MM HH:mm:ss ZZZ"];
从您拥有的格式的字符串中创建一个 NSDate 。那么应该可以工作。
如果您需要返回 NSDateFormatterMediumStyle 格式的 NSString,那么只有在获得 NSDate 后,您才能将其应用到 dateFormatter 对象,就像您所做的那样:
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
然后使用此 dateFormatter 从您获得的日期中获取字符串:
NSString *formattedDate = [dateFormatter stringFromDate:date];
关于iphone - 如何格式化 NSFetchedResultsSectionInfo 中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9675583/