2012-12-13 92 views
1

我需要對一年內進行的日誌進行一些基於時間的統計, 我需要做的就是確定一個確定內的(太陽)周的數量日期範圍。計算日期範圍內的星期數

即我需要計算2011年8月1日至2012年9月3日之間已經發生了多少星期。

我已經有了計算兩個日期之間的日子然後除以7的想法,但是這並不能說明我可能在幾個星期之間的事實,在這種情況下,價值將不會是正確的/精確。

以前有人遇到過類似的問題嗎?

回答

6

我假設你在NSDates(date1和date2)中有兩個日期。然後調用

NSCalendar *calendar = [NSCalendar currentCalendar]; 
//declare your unitFlags 
int unitFlags = NSWeekCalendarUnit; 

NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date1 toDate:date2 options:0]; 

int weeksInBetween = [dateComponents week]; 

希望幫助

+0

我使用此代碼,但Xcode返回警告。 [dateComponents week]似乎已被棄用。任何想法現在如何工作? –

+2

您可以使用weekOfYear或weekOfMonth,具體取決於您的需要。 –

0
NSDateComponents *difference = [[NSCalendar currentCalendar] components:NSCalendarUnitDay 
                   fromDate:startDate] 
                   toDate:endDate] 
                   options:0]; 
NSInteger weeksDiffCount = (((NSInteger)[difference day])/7); 

希望它有幫助。

相關問題