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

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 に答える