1

我想要一个函数,它以周数作为输入并返回该特定周的所有 NSDates 的数组。

像这样的东西:

-(NSArray*)allDatesInWeek:(int)weekNumber {
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setFirstWeekday:2];
    NSDateComponents *todayComp = [calendar components:NSYearCalendarUnit fromDate:today];
    int currentyear = todayComp.year;
    /* Calculate and return the date of weekNumber for current year */

}

如何以简单的方式做到这一点?

4

2 回答 2

5

这个解决方案完全依赖于 NSCalendar,而不对用户的日历做任何假设。

-(NSArray*)allDatesInWeekContainingDate:(NSDate*)referenceDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger ordinalityOfInput = [calendar ordinalityOfUnit:NSWeekdayCalendarUnit
                                                      inUnit:NSWeekCalendarUnit
                                                     forDate:referenceDate];
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
    componentsToAdd.day = -1 * (ordinalityOfInput - 1);
    NSDate *startDate = [calendar dateByAddingComponents:componentsToAdd toDate:referenceDate options:0];
    NSInteger numDaysInWeek = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
    NSMutableArray *allDays = [NSMutableArray arrayWithCapacity:numDaysInWeek];
    NSDateComponents *curDayOffset = [[NSDateComponents alloc] init];
    for (int curDay=0; curDay < numDaysInWeek; curDay++) {
        curDayOffset.day = curDay;
        [allDays addObject:[calendar dateByAddingComponents:curDayOffset toDate:startDate options:0]];
    }
    return allDays;
}
于 2013-12-06T19:56:48.423 回答
1

经测试。

-(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 中所述。如果需要,可以调整。

于 2012-06-09T00:14:49.890 回答