iphone - 如何格式化 NSFetchedResultsSectionInfo 中的日期?

标签 iphone ios

我希望能够干净地格式化表格部分标题中的日期。这是我的代码:

- (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/

相关文章:

iphone - Objective-C 等效于 curl 请求

iphone - iPad 在加载带有音频标签的 div 时模糊页面

ios - Textfield 的文本必须看起来有点正确

ios - 渐变不填充 IBDesignable UIView

ios - 如何在 NSInputStream 上设置编码类型?

iphone - 在我的应用程序中使用类似于 iBook 的 3D View 转动过渡是否安全?

iphone - iOS iPhone Phonegap HTML App 滚动条和设备宽度问题

ios - 核心数据子查询语法问题

ios - 新应用程序提供应用程序内购买。版本

ios - UIView 与 UITableviewcontroller Swift 顶部的标签