2015-07-21 107 views
0

我計算月和日兩個日期之間使用NSCalendar返回兩個不同的日期

- NSCalendar components:fromDateComponents:toDateComponents:options: 

有趣的是我得到了兩個不同的日子同樣的結果差別同一日期成分差:

  • 2014-07-30 - 2015-07-20:10個月20天
  • 2014-07-31 - 2015-07-20:10個月20天

一個完整的命令行程序,以重現要點是在這裏:https://gist.github.com/p2/a1f7ad6acc9d555ee00b

相關部分:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
NSCalendarUnit flags = NSCalendarUnitMonth | NSCalendarUnitDay; 
NSDateComponents *rslt = nil; 

// between 7/30/2014 and 7/20/2015: 11 months 21 days 
NSDateComponents *later = [NSDateComponents new]; 
later.year = 2015; 
later.month = 7; 
later.day = 20; 

NSDateComponents *earlier = [NSDateComponents new]; 
earlier.year = 2014; 
earlier.month = 7; 
earlier.day = 30; 

rslt = [calendar components:flags fromDateComponents:earlier toDateComponents:later options:0]; 
// rslt.month is 11, rslt.day is 20 

// between 7/31/2014 and 7/20/2015: 11 months 20 days 
earlier.day = 31; 

rslt = [calendar components:flags fromDateComponents:earlier toDateComponents:later options:0]; 
// rslt.month is 11, rslt.day is 20 

任何人能解釋這是怎麼回事,問題可能是什麼?

回答

0

原來我是個白癡,電腦再次正確。感謝羅布指出的明顯:

在這種情況下,2014-07-30 11個月是2015-06-30,從2014-07-31 11個月也是2015-06-30。 (畢竟,你不希望它是2015-07-01)。 此日期後20天爲2015-07-20。

所以從2014-07-30和2015-07-31到2015-07-20的時間是11個月和20天。

相關問題