2011-09-23 74 views
-1

如何使用NSDateComponents獲得週三和週五的未來日期?答案將不勝感激。提前致謝。如何獲得未來日期

+3

(http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

回答

3

這實際上是一個棘手的問題,如果你想它是完全防彈的。這是我會怎麼做:?你嘗試過什麼]

NSInteger wednesday = 4; // Wed is the 4th day of the week (Sunday is 1) 
NSInteger friday = 6; 

NSDate *start = ...; // your starting date 
NSDateComponents *components = [[NSDateComponents alloc] init]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

for (int i = 0; i < 100; ++i) { 
    [components setDay:i]; 
    NSDate *target = [gregorian dateByAddingComponents:components toDate:start options:0]; 
    NSDateComponents *targetComponents = [gregorian components:NSUIntegerMax fromDate:target]; 
    if ([targetComponents weekday] == wednesday || [targetComponents weekday] == friday) { 
    NSLog(@"found wed/fri on %d-%d-%d", [targetComponents month], [targetComponents day], [targetComponents year]); 
    } 
} 

[gregorian release]; 
[components release]; 
+0

它的工作原理!。非常感謝.. – isarathg

0

要獲得正確的星期幾,您必須創建一個合適的NSCalendar實例,使用dateFromComponents創建一個NSDate對象:然後使用components:fromDate:來檢索星期幾。

NSDate *yourDate = ... 
NSDateComponents* components = [[NSDateComponents alloc] init]; 
components.week = weeks; 
NSDate* futureDate = [[NSCalendar reCurrentCalendar] dateByAddingComponents:components toDate:yourDate options:0]; 
[components release]; 

附註:

0

如果您有具體平日NSDate實例指標(如星期三),您可以通過下面的代碼獲得未來的新日期同意Brian的意見,在提問前嘗試研究。