经测试。
-(NSArray*)allDatesInWeek:(int)weekNumber {
// determine weekday of first day of year:
NSCalendar *greg = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *coms = [[NSDateComponents alloc] init];
comps.day = 1;
NSDate *today = [NSDate date];
NSDate *tomorrow = [greg dateByAddingComponents:comps toDate:today];
const NSTimeInterval kDay = [tomorrow timeIntervalSinceDate:today];
comps = [greg components:NSYearCalendarUnit fromDate:[NSDate date]];
comps.day = 1;
comps.month = 1;
comps.hour = 12;
NSDate *start = [greg dateFromComponents:comps];
comps = [greg components:NSWeekdayCalendarUnit fromDate:start];
if (weekNumber==1) {
start = [start dateByAddingTimeInterval:-kDay*(comps.weekday-1)];
} else {
start = [start dateByAddingTimeInterval:
kDay*(8-comps.weekday+7*(weekNumber-2))];
}
NSMutableArray *result = [NSMutableArray array];
for (int i = 0; i<7; i++) {
[result addObject:[start dateByAddingTimeInterval:kDay*i]];
}
return [NSArray arrayWithArray:result];
}
这假设一周的第一天是星期日,如 NSDate API 中所述。如果需要,可以调整。