菜鸟教程小白 发表于 2022-12-12 21:42:21

ios - NSDateFormatter 和 NSDateComponents 为周数返回不同的值


                                            <p><p>我正在制作一个创建时间表的应用程序。您可以在一年中的每周创建一个新的。当应用程序完成加载后,需要加载当前周(例如:如果是 1 月 1 日,则需要显示第 1 周)。我使用 NSDateFormatter 来确定本周是什么。</p>

<p><strong>NSDateFormatter</strong></p>

<p>(我在 2016 年 8 月 9 日对此进行了测试)</p>

<pre><code>NSDateFormatter *dateFormatter = [ init];
;

int currentWeek = [] intValue];
</code></pre>

<p>我想检查它是否工作,所以我使用了 NSLog。</p>

<pre><code>NSLog(@&#34;%i&#34;, currentWeek);
</code></pre>

<p>它返回 <code>32</code>。</p>

<p><strong>NSDateComponents</strong></p>

<p>所以 NSDateFormatter 认为当前周是 <code>32</code>。到目前为止,一切都很好。应用程序需要发送一个推送通知来告诉用户某个时间段即将开始。所以应用程序使用 NSDateComponents 安排通知。</p>

<pre><code>// Setting the notification&#39;s fire date.
NSCalendar *calendar = [ initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComps = [ init];
;// Because it&#39;s on a Tuesday
;// 32
;
;
;
NSDate *theFireDate = ;

// Creates the notification.
UILocalNotification *Alert = [ init];
Alert.timeZone = ;
Alert.alertBody = @&#34;This is a message!&#34;;
Alert.fireDate = theFireDate;
[ scheduleLocalNotification:Alert];
</code></pre>

<p>而且我还使用了 NSLog。</p>

<pre><code>NSLog(@&#34;%@&#34;, theFireDate);
</code></pre>

<p>但它返回的 <code>2016-08-02 12:20:00 +0000</code> 不是当前日期。它实际上是当前日期减去 7 天,或提前一周。那么这是否意味着当前周实际上是 <code>33</code> 而不是 <code>32</code>,这意味着 NSDateFormatter 是错误的?或者它实际上是 <code>32</code> 这意味着 NSDateComponents 是错误的。是什么导致了这两者之间的差异?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>不要使用<code>NSDateFormatter</code>,使用更准确的<code>NSCalendar</code>。</p>

<pre><code>NSCalendar *calendar = [ initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSInteger weekOfYear = ];
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - NSDateFormatter 和 NSDateComponents 为周数返回不同的值,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38855170/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38855170/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - NSDateFormatter 和 NSDateComponents 为周数返回不同的值