菜鸟教程小白 发表于 2022-12-11 21:59:49

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


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

<pre><code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id &lt;NSFetchedResultsSectionInfo&gt; sectionInfo = [ objectAtIndex:section];
NSDateFormatter *dateFormatter = [init];
;
NSDate *date = ;
NSString *formattedDate = ;
NSLog(@&#34;%@&#34;, formattedDate);
return formattedDate;
}
</code></pre>

<p>使用此代码,不会出现任何节标题,因为日期为空。由于某种原因 dateFromString 无法将字符串 sectionInfo.name 转换为 NSDate。有什么建议吗?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>考虑到您的评论,您指出日期标题的格式是 2012-03-12 07:00:00 +0000,您可以确定问题出在格式上。</p>

<p>NSDateFormatterMediumStyle 的格式为“1937 年 11 月 23 日” - 这是您的不匹配 :)</p>

<p>你必须使用类似的东西:</p>

<pre><code>;
</code></pre>

<p>从您拥有的格式的字符串中创建一个 NSDate。那么应该可以工作了。</p>

<p>如果您需要返回一个具有 NSDateFormatterMediumStyle 格式的 NSString,那么只有在您获得 NSDate 之后,您才能将其应用于您的 dateFormatter 对象:</p>

<pre><code>;
</code></pre>

<p>然后使用这个 dateFormatter 从你得到的日期获取字符串:</p>

<pre><code>NSString *formattedDate = ;
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于iphone - 如何从 NSFetchedResultsSectionInfo 格式化日期?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/9675583/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/9675583/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iphone - 如何从 NSFetchedResultsSectionInfo 格式化日期?