我有一个日期选择器。

从中选择一个时间后,我想获取下一个64个星期一的日期。

我将如何编写一种获取日期并从该日期起的下一个64个星期一返回NSDates的NSArray的方法

例如
我从日期选择器中选择了下午6:45的时间,然后我想获取接下来的64个星期一的时间,并将该时间设置为该时间。

最佳答案

范例(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);
}

NSLog输出:
PickerDate:2011-12-09 20:38:25 +0000
星期#:0,星期一日期:2011-12-12 20:38:25 +0000
星期#:1,星期一日期:2011-12-19 20:38:25 +0000
周#:2,星期一日期:2011-12-26 20:38:25 +0000
周#:3,星期一日期:2012-01-02 20:38:25 +0000
-剩下的60个-

10-08 14:41