2011-10-22 158 views
0

在我的應用程序中,我得到兩個日期。iPhone:如何查找兩個選定日期之間的日期?

例如,

1日期:2011-10-28

第2日期:2011年2月11日

現在,我想這兩個選定日期間的所有日期。

所以它應該是,

2011-10-28

29-10-2011

30-10-2011

2011年1月11日

2-11-2011

我怎樣才能使用NSDate得到這個?

+0

http://stackoverflow.com/questions/3357257/simplest-way-to-loop-between-two-nsdates-on-iphone –

回答

6

嘗試dateWithTimeInterval:SinceDate:

NSMutableArray dates = [NSMutableArray array]; 
NSDate *curDate = startDate; 
while([curDate timeIntervalSince1970] <= [endDate timeIntervalSince1970]) //you can also use the earlier-method 
{ 
    [dates addObject:curDate]; 
    curDate = [MSDate dateWithTimeInterval:86400 sinceDate:curDate]; 86400 = 60*60*24 
} 
//here maybe an additional check if the enddate has to be inserted or not 
+1

添加86400秒還能在夏令時發生的日子裏工作嗎?這樣的日子可能會長一小時或更短...... – dokaspar

0

您可以使用NSDateFormatter將字符串轉換爲NSDate對象,然後使用NSDate的ealierDate:和laterDate:方法來比較它們。

0
NSDate *today = [NSDate date]; 
NSDate *startDate = [NSDate date]; 
NSDate *endDate = [today addTimeInterval:10.0*60.0*60.0*24.0]; // end date 10 days ahead 
while (YES) { 

    startDate= [startDate addTimeInterval:1.0*60.0*60.0*24.0]; 
    NSLog(@"%@ -- %@",endDate,startDate); 

    if([startDate compare:endDate]==NSOrderedDescending) break; 
} 
3

NSDateComponentsdateByAddingComponents:toDate:options:,這是我使用和它的作品相當不錯的。請務必留意閏年。

更新:我會用thomas的例子。它比我的效果更好,閱讀起來更容易。

+1

但是他在時鐘變化方面不太可靠。 –

相關問題