ios - NSCalendar 的 dateBySettingUnit 方法返回不明显的结果
<p><p>NSDateComponents 解决了我的问题,但我想了解为什么这种方法如此有效</p>
<pre><code>NSDate *today = ;
NSLog(@"today is: %@", today);
NSDate *dayChanged = [calendar dateBySettingUnit:(NSCalendarUnitDay)
value:10
ofDate:today
options:0];
NSLog(@"dayChanged is: %@", dayChanged);
NSDate *monthChanged = [calendar dateBySettingUnit:(NSCalendarUnitMonth)
value:5
ofDate:today
options:0];
NSLog(@"monthChanged is: %@", monthChanged);
</code></pre>
<p>结果是:</p>
<pre><code>today is: 2016-09-30 06:40:36 +0000
dayChanged is: 2016-10-10 00:00:00 +0000
monthChanged is: 2017-05-01 00:00:00 +0000
</code></pre>
<p>为什么 <code>dateBySettingUnit</code> 增加下一个更大的单位?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>根据观察,<a href="https://forums.developer.apple.com/thread/12048" rel="noreferrer noopener nofollow">dateBySettingUnit does not return past date</a> </p>
<p>因此,对于使用 <code>dateBySettingUnit</code> 对 future 日期的快速测试设置可以按预期工作,请参见以下代码:</p>
<pre><code>NSCalendar *calendar = [ initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *today = ;
NSLog(@"today is: %@", today);
NSDate *dayChanged = [calendar dateBySettingUnit:(NSCalendarUnitDay)
value:31
ofDate:today
options:NSCalendarWrapComponents];
NSLog(@"dayChanged is: %@", dayChanged);
NSDate *monthChanged = [calendar dateBySettingUnit:(NSCalendarUnitMonth)
value:12
ofDate:dayChanged
options:NSCalendarWrapComponents];
NSLog(@"monthChanged is: %@", monthChanged);
</code></pre>
<p>日志:</p>
<pre><code>2016-09-30 12:58:30.506 TestRegex today is: 2016-09-30 07:58:30 +0000
2016-09-30 12:58:30.508 TestRegex dayChanged is: 2016-09-30 19:00:00 +0000
2016-09-30 12:58:30.509 TestRegex monthChanged is: 2016-11-30 19:00:00 +0000
</code></pre>
<p>您可以尝试实际计算偏移量的链接答案中提到的 NSCalendar 扩展,或者您可以使用 <code>NSDateComponents</code>
解决方案:</p>
<pre><code> NSDateComponents *comps = [ components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:today];
;
;
</code></pre>
<p>希望有帮助!</p></p>
<p style="font-size: 20px;">关于ios - NSCalendar 的 dateBySettingUnit 方法返回不明显的结果,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/39785430/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/39785430/
</a>
</p>
页:
[1]