0

前の週の日の配列を取得するにはどうすればよいですか? たとえば、今日は 2013 年 4 月水曜日です。これは、週の最初の日が日曜日の場合、週の 4 日目です。「sunday/25/2013」、mon/26/2013、..... sat/31/2013 の配列が必要ですか? 私はこれをやっていますが、助けが必要ではありませんでした..

 NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *currentComps = [myCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:weekDate];
int ff = currentComps.weekOfYear;
NSLog(@"1  %d", ff);


[currentComps setDay:2]; // 1: sunday
[currentComps setWeek: [currentComps week] - 1];
NSLog(@"currentComps setWeek:>>>>>>  %@", currentComps);
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
NSLog(@"firstDayOfTheWeek>>>>>>  %@", firstDayOfTheWeek);
NSString *firstStr = [myDateFormatter stringFromDate:firstDayOfTheWeek];
lbl_Day1.text = firstStr;
4

1 に答える 1

4
// Start with some date, e.g. now:
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];

// Compute beginning of current week:
NSDate *date;
[cal rangeOfUnit:NSWeekCalendarUnit startDate:&date interval:NULL forDate:now];

// Go back one week to get start of previous week:
NSDateComponents *comp1 = [[NSDateComponents alloc] init];
[comp1 setWeek:-1];
date = [cal dateByAddingComponents:comp1 toDate:date options:0];

// Some output format (adjust to your needs):
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"EEEE dd/MM/yyyy"];

// Repeatedly add one day:
NSDateComponents *comp2 = [[NSDateComponents alloc] init];
[comp2 setDay:1];
for (int i = 1; i <= 7; i++) {
    NSString *text = [fmt stringFromDate:date];
    NSLog(@"%@", text);
    date = [cal dateByAddingComponents:comp2 toDate:date options:0];

}

出力:

2013/08/25 日曜日
2013/08/26 月曜日
2013/08/27 火曜日
2013/08/28 水曜日
2013/08/29 木曜日
2013/08/30 金曜日
2013/08/31 土曜日

追加(コメントへの返信):

NSDateComponents *comp2 = [[NSDateComponents alloc] init];
[comp2 setDay:1];

// First day:
lbl_Day1.text = [fmt stringFromDate:date];

// Second day:
date = [cal dateByAddingComponents:comp2 toDate:date options:0];
lbl_Day2.text = [fmt stringFromDate:date];

// Third day:
date = [cal dateByAddingComponents:comp2 toDate:date options:0];
lbl_Day3.text = [fmt stringFromDate:date];

// and so on ...
于 2013-09-04T15:42:22.660 に答える