2013-07-30 33 views

回答

5

以下代碼的想法是計算開始日期之後給定的工作日 的第一次出現,然後計算剩餘 到結束日期的週數。

NSDate *fromDate = ...; 
NSDate *toDate = ...; 
NSUInteger weekDay = ...; // The given weekday, 1 = Sunday, 2 = Monday, ... 
NSUInteger result; 

// Compute weekday of "fromDate": 
NSCalendar *cal = [NSCalendar currentCalendar]; 
NSDateComponents *c1 = [cal components:NSWeekdayCalendarUnit fromDate:fromDate]; 

// Compute next occurrence of the given weekday after "fromDate": 
NSDateComponents *c2 = [[NSDateComponents alloc] init]; 
c2.day = (weekDay + 7 - c1.weekday) % 7; // # of days to add 
NSDate *nextDate = [cal dateByAddingComponents:c2 toDate:fromDate options:0]; 

// Compare "nextDate" and "toDate": 
if ([nextDate compare:toDate] == NSOrderedDescending) { 
    // The given weekday does not occur between "fromDate" and "toDate". 
    result = 0; 
} else { 
    // The answer is 1 plus the number of complete weeks between "nextDate" and "toDate": 
    NSDateComponents *c3 = [cal components:NSWeekCalendarUnit fromDate:nextDate toDate:toDate options:0]; 
    result = 1 + c3.week; 
} 

(代碼假設一個星期有七天,這是公曆如此。 如果有必要,該代碼很可能廣義任意日曆工作。)

+2

上述泛化應該像使用'[cal rangeOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:fromDate]'替換硬件7一樣簡單。 –

0
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:[NSDate date]]; 
//pass different date in fromDate and toDate column. 
+2

的問題是,(如果我理解正確)有多少例如星期日在兩個給定日期之間。 –

+0

我要在哪裏指定日期,即(星期一或星期二或星期五等)?因爲我想只計算某個特定的工作日的發生次數。 – DemonicPossessions1991

+0

@MartinR:當然是,不僅僅是週日。它可以是一週中的任何一天。例如星期一或星期二或任何其他日子,但是,是的,沒錯,你讓我正確.. – DemonicPossessions1991

相關問題