0

如何获得前一周的几天?例如 - 今天是 wed/04/2013,如果一周的第一天是星期天,这是一周的第四天。我需要带有'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];

}

输出:

星期日 25/08/2013
星期一 26/08/2013
星期二 27/08/2013
星期三 28/08/2013
星期四 29/08/2013
星期五 30/08/2013
星期六 31/08/2013

添加(回复您的评论):

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 回答