OGeek|极客世界-中国程序员成长平台

标题: iphone - 如何从 NSFetchedResultsSectionInfo 格式化日期? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 21:59
标题: iphone - 如何从 NSFetchedResultsSectionInfo 格式化日期?

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

- (NSString *)tableViewUITableView *)tableView titleForHeaderInSectionNSInteger)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。有什么建议吗?



Best Answer-推荐答案


考虑到您的评论,您指出日期标题的格式是 2012-03-12 07:00:00 +0000,您可以确定问题出在格式上。

NSDateFormatterMediumStyle 的格式为“1937 年 11 月 23 日” - 这是您的不匹配

你必须使用类似的东西:

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






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4