获得一系列未来的NSDates

Aya*_*avi 7 cocoa-touch objective-c ios

我有一个约会选择器.

从中选择一个时间后,我想得到接下来的64个星期一的日期.

我将如何编写一个方法来获取日期,并在该日期的下一个64个星期一返回NSArray的NSDrray

例如,我从日期选择器下午6:45选择了时间,然后我想获取下一个64个星期一,时间设置为那个时间.

zap*_*aph 3

示例(ARC):

NSDate *pickerDate = [NSDate date];
NSLog(@"pickerDate: %@", pickerDate);

NSDateComponents *dateComponents;
NSCalendar *calendar = [NSCalendar currentCalendar];

dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate];
NSInteger firstMondayOrdinal = 9 - [dateComponents weekday];
dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:firstMondayOrdinal];
NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0];

dateComponents = [[NSDateComponents alloc] init];
[dateComponents setWeek:1];

for (int i=0; i<64; i++) {
    [dateComponents setWeek:i];
    NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0];
    NSLog(@"week#: %i, mondayDate: %@", i, mondayDate);
}
Run Code Online (Sandbox Code Playgroud)

NSLog 输出:
pickerDate:2011-12-09 20:38:25 +0000
week#: 0,星期一Date:2011-12-12 20:38:25 +0000
week#:1,mondayDate:2011-12-19 20: 38:25 +0000
周#: 2, 星期一日期: 2011-12-26 20:38:25 +0000
周#: 3, 星期一日期: 2012-01-02 20:38:25 +0000
-剩余 60 个在这里-