2011-04-06 87 views
0

我使用計算兩個日期之間的差異月:NSDate的問題

NSInteger month = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit fromDate: start toDate: end options: 0] month]; 

當計算的幾個月裏,我有一個小問題。假設:

startdate = 01/05/2005; (dd/mm/yyyy) enddate = 01/06/2005; (dd/mm/yyyy)

月份差異返回爲0.我注意到要返回正確的結果(在本例中爲1),我需要將enddate設置爲開始日期的+1天。那麼,02/06/2005。我怎麼能解決這個問題?

回答

0

但差異是0個月,因爲它是同一個月。如果您希望表示同一個月爲一個月,並且「下一個」月份爲2,那麼您是否可以簡單地將結果加1?

+0

5和6是不一樣的一個月。 :-) – 2011-04-06 18:34:42

+0

哎呀!誤讀了! :d – joshpaul 2011-04-06 18:45:08

0

聽起來像你的意見輸入被誤解。你如何創建開始和結束對象?您是否驗證過您的輸入數據按照您的意圖解釋爲dd/mm/yyyy,而不是mm/dd/yyyy?

如果第一個組件('01'爲開始和結束)被解釋爲月份而不是一天,則差值0將是完全正確的。另外,在結束日期中使用'02'將(再次,正確)按照您描述的方式行事,如果是這樣的話。

0

這爲我工作,但我沒有給它太多,但它是否是最好的解決辦法:

NSDate* dateA; // alloc and init 
NSDate* dateB; // alloc and init 

NSCalendar *sysCalendar = [NSCalendar currentCalendar]; 
unsigned int unitFlags = NSSecondCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit; 

NSDateComponents *difference= [sysCalendar components:unitFlags fromDate: dateA toDate:dateB options:0]; 

double hour = [difference hour]; 
double minute = [difference minute]; 
double second = [difference second]; 

我的目標在這裏是無視上述小時什麼。這就是我設置NSDayCalendarUnit標誌的原因。如果你設置了NSMonthCalendarUnit-flag(?),它應該總共提供幾個月,而不僅僅是dateA的month - dateB的月份。

編輯:我得到這個從另一個線程,但無法弄清楚它,所以謝謝你與誰這段代碼:)

1

嘗試時區設置爲UTC提供的我。

下面是示例代碼,返回1代表差異。

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
[formatter setDateFormat:@"dd/MM/yyyy"]; 
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 

NSDate * start = [formatter dateFromString:@"01/05/2005"]; 
NSDate * end = [formatter dateFromString:@"01/06/2005"];  

NSInteger month = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit fromDate: start toDate: end options: 0] month]; 
NSLog(@"%@, %@ --> difference: %d", start, end, month); 
0

你不這樣做,你應該......

NSDate *start = [NSDate date]; 
NSDate *end = [NSDate date]; 

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
start = [dateFormatter dateFromString:@"01-05-2005"]; 
end = [dateFormatter dateFromString:@"01-06-2005"]; 

NSInteger month = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit fromDate: start toDate: end options: 0] month]; 
NSLog(@"%i", month);