• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - 如何从 NSFetchedResultsSectionInfo 格式化日期?

[复制链接]
菜鸟教程小白 发表于 2022-12-11 21:59:49 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

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

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap